I'm using google maps api and I need to keep the last center and zoom level everytime I reload the page.
I have this parameters in PHP variables, how can I change initMap function and pass these parameters to it?
The problem is that we are calling the function this way:
<script src="https://maps.googleapis.com/maps/api/js?key=*******&callback=initMap" async defer></script>
You can't pass arguments to the callback(at least not via the way you load the maps-API)
A possible workaround: store the parameters as attribute of the script-tag, then you'll be able to access them in the callback:
<?php
//your parameters, defined in PHP
$goo=array('zoom'=>14,'center'=>array('lat'=>52.549,'lng'=>13.425));
?>
<div id="map_canvas"></div>
<script>
function initMap(){
var opts = {
zoom: 0,
center: new google.maps.LatLng(0,0),
mapTypeId: google.maps.MapTypeId.ROADMAP
},
script= document
.querySelector('script[src^="https://maps.googleapis.com/maps/api/js"][data-goo]'),
custom;
if(script){
custom=JSON.parse(script.getAttribute('data-goo'));
for(var k in custom){
opts[k]=custom[k];
}
}
map = new google.maps.Map(document.getElementById('map_canvas'),
opts);
}
</script>
<script data-goo="<?php echo htmlentities(json_encode($goo));?>"
src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=***" async defer>
</script>
Another option would be the loader of the JSAPI, where you have the option to define a function-reference(instead of a function-name) as callback:
<?php
//your parameters, defined in PHP
$goo=array('zoom'=>14,'center'=>array('lat'=>52.549,'lng'=>13.425));
?>
<div id="map_canvas"></div>
<script>
function initMap(params){
var opts = {
zoom: 0,
center: new google.maps.LatLng(0,0),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
for(var k in params){
opts[k]=params[k];
}
map = new google.maps.Map(document.getElementById('map_canvas'),
opts);
}
</script>
<script src="https://www.google.com/jsapi"></script>
<script>
google.load('maps',
'3',
{ other_params :'key=***',
callback : (function(params){return function(){initMap(params);}})
(<?php echo json_encode($goo);?>) });
</script>
However, as it sounds the desired data(last zoom/center) at first is available on clientSide, so there is no reason to store it on serverSide.
Just store it via sessionStorage(as suggested by #RamRaider ) or even cookies, and read it from the client when you need it.
Related
I have javascript for a google map and need to put php variables in where the longitude and latitude values are, but I am unsure on how to do allow javascript to work inside a php file, how do I do this?
Here is the code I am using:
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: **-34.397**, lng: **150.644**},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/jskey=MYAPIKEY&callback=initMap"
async defer></script>
What I need is to change the "lat: " and "long: " to have two php variables in it, for example:
lat: $myVariableLat;
lng: $myVariableLng;
And have the javascript above working inside my php file
I'm assuming there's a webserver in your setup running a .php file(s) that is displaying a webpage.
You need to understand that the .php file is just rendering the result of it's contents. This means you need to embed the variable you care about into the html /javascript you're wanting displayed.
If the above is valid, the contents of your .php file would look something like this.
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: <?php echo $myVariableLat; ?>, lng: <?php echo $myVariableLng; ?>},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/jskey=MYAPIKEY&callback=initMap"
async defer></script>
JavaScript runs client-side, PHP gets executed before the document/data is even sent.
If your longitude and latitude don't need to dynamically change then you can use this php code:
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: <?=$myVariableLat?>, lng: <?=$myVariableLng?>},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/jskey=MYAPIKEY&callback=initMap"
async defer></script>
PHP will run and insert the values in your JavaScript.
<?= opens a new php tag and echos the following value. ?> just closes the php tag
The result should look like this:
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/jskey=MYAPIKEY&callback=initMap"
async defer></script>
Hi :) I need some help for this. I have a problem on how to show my modals in simply clicking the "View Location" button inside the table. Once I hit it the modals will show but I cant do this. Here' s my code:
echo "<td>View Location</td>";
echo "<td>Edit</td>";
echo "<td>Delete</td><tr>";
This is my js coming from the free source:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function ic() {
$("#btnShow").click(function ic() {
$("#dialog").dialog({
modal: true,
title: "Google Map",
width: 600,
hright: 450,
buttons: {
Close: function ic() {
$(this).dialog('close');
}
},
open: function ic() {
var mapOptions = {
center: new google.maps.LatLng(14.8527393, 120.8160376),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map($("#dvMap")[0], mapOptions);
}
});
});
});
</script>
My problem is in this part echo "View Location";
I have no idea to make it functional. Is anyone here knows how to solve this? Thanks for helping!
If you are using PHP try this:
echo "<td><button id="btnShow">View Location</button></td>";
echo "<td>Edit</td>";
echo "<td>Delete</td><tr>";
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("#btnShow").click(function ic() {
$("#dialog").dialog({
modal: true,
title: "Google Map",
width: 600,
hright: 450,
buttons: {
Close: function ic() {
$(this).dialog('close');
}
},
open: function ic() {
var mapOptions = {
center: new google.maps.LatLng(14.8527393, 120.8160376),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map($("#dvMap")[0], mapOptions);
}
});
});
});
</script>
The jQuery syntax $("#btnShow").click is saying "When something with an ID of btnShow is clicked."
Therefore, by giving your link an ID of btnShow, you'll cause the function to fire.
echo "<td><a href='' id='btnShow'>View Location</a></td>";
echo "<td>Edit</td>";
echo "<td>Delete</td><tr>";
If you want the button to have a hand cursor, you may want echo "<td><a style='cursor: pointer;' href='' id='btnShow'>View Location</a></td>";
EDIT: I think I've misunderstood. If you're trying to popup a location based on the person, and not have the page change windows, you'll have to do this through AJAX.
The PHP would be something like:
echo "<td><a href='' onclick='btnShow(".$query2['ID'].")'>View Location</a></td>";
Essentially what the code above does now is call a jquery function called "btnShow(ID)" which you'd have to create. This function would do an AJAX call to a PHP page that grabs the latitude and longitude from a server based on the ID you've passed. On success, it would then call your 'free source' formula, replacing the latitude and longititude with the values retrieved from the AJAX call.
I realize this sounds daunting but jQuery makes AJAX calls much easier than they sound. I wish I had more time at the moment to type out a function for you, however I do not. I hope this at least moved you in the right direction though!
EDIT 2: To be clear, the function that you're calling right now - the free source one - has a set latitude and longitude. No matter what "View Location" button you click, it will ALWAYS show the same location. If you're trying to do this, then I can give you a simple script.
However, if you're trying to change location based on the person, this is way more in depth, and would be achieved using the method I've outlined in my original edit.
I want to add a marker into existing google map, from data received by my web service. I get the latitude and the longitude with no problems. But I canĀ“t figure out how to this. Here go my code, and what I try to do:
<html>
<head>
...
<script>
function initialize(){
var mapProp = {
center:new google.maps.LatLng(25,-30),
zoom:2,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap") ,mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
...
<div class="col-md-8">
<div id="googleMap" style="width:700px;height:350px; border-radius:20px;"></div>
</div>
...
<script src="../front-end/js/main.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#jogadoresList").click(function () {
$("#index").hide();
$("#selecoes").hide();
$("#jogador").show();
initialize();
});
});
</body>
main.js
function findByIdLocationTwitterJogador(id){
console.log('findJTwitterByJogadorrrrrr AQUIIIIIIIIII' + id);
$.ajax({
type: 'GET',
url: rootURLLocalizacao +'/' + id,
dataType: "json", // data type of response
success: renderListLocalizacao
});
}
function renderListLocalizacao(data) {
// JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one')
var list = data == null ? [] : (data.dados instanceof Array ? data.dados : [data.jogo]);
$.each(list, function(index, jogo) {
var myLatlng = new google.maps.LatLng(jogo.latitude,jogo.longitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Former About.com Headquarters"
});
});
}
The issue here is that the "map" object is not visible from the renderListLocalizacao(...) function. Note how your map is created inside the scope of your initialize()
Try making the map a global var. If you dump / look at its value while running that function, I am guessing you will see map as undefined.
Please set a global map object as follows
<script>
var globalMap=null;
function initialize(){
var mapProp = {
center:new google.maps.LatLng(25,-30),
zoom:2,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
globalMap=new google.maps.Map(document.getElementById("googleMap") ,mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
and in renderListLocalizacao
function renderListLocalizacao(data) {
// JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one')
var list = data == null ? [] : (data.dados instanceof Array ? data.dados : [data.jogo]);
$.each(list, function(index, jogo) {
var myLatlng = new google.maps.LatLng(jogo.latitude,jogo.longitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: globalMap,
title:"Former About.com Headquarters"
});
});
I am using google maps in one of my jquery mobile pages, and instead of loading the whole maps javascript files on every page, I've included them into the page in which google maps is used.
But when I navigate to the page, the loading spinner is spinning and spinning around but nothing happens. When I delete the gmaps code everything works fine.
I use this plugin so my code looks like that:
<div data-role="page" id="page1" data-theme="a">
<?php include "components/site_header.php"; ?>
<!-- Scripts for Maps -->
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script src="library/jquery.ui.map.full.min.js" type="text/javascript"></script>
<!--.................-->
<div data-role="content">
<div id="map_canvas" style="width:100%;height:250px"></div>
<script type="text/javascript">
$(function() {
var LatLng = new google.maps.LatLng(<?=$lat;?>, <?=$lon;?>);
$('#map_canvas').gmap({'center': LatLng});
});
</script>
</div>
</div>
</div>
EDIT The code is working when I call the webpage directly (over the URL). But it is loading endlessly when I navigate to it through the website...
EDIT2 Got the code to work. Removed the plugin which I stated above and added the Google Maps JS file BEFORE the Jquery and Jquery Mobile JS. And my code looks now like this:
<div id="map_canvas" style="width:100%;height:250px"></div>
<script type="text/javascript">
var address = '<?php echo $info['pr_city'].", ".$info['pr_zip'].", ".$info['pr_street'].", ".$info['pr_nr']; ?>';
var map = new google.maps.Map(document.getElementById('map_canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 15
});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
map.setCenter(results[0].geometry.location);
}
});
</script>
I am very new in HTML5 area, I am trying to make a program that will fetch the data from mysql with PHP and use geocode to transform from address to Latlng. it is a LBS program, and I was trying for 2 weeks, my question is I cannot put markers into the Google MAP, I did the locator corrected and map is loaded, but the marker cannot land on map, please help!! thank you, and I am really appreciate your help. if this code has any mistake or problem please give me generous advice, I am very new in this area, and I am trying to learn more in HTML5 Javascript, thank you and I am very appreciate your advice!!!
my code is here:
'enter code here`<?php
require_once 'Common/system_start.php';
$sql="select addr from tab_mem order by sn desc ";
$result= mysql_query($sql);
$data=mysql_fetch_assoc($result);
$row=mysql_num_rows($result);
$n = array();
for($i=0;$i<$rows;$i++)
{
$data=mysql_fetch_row($result);
$n[] = $data[0];
}
echo '<script type="text/javascript">';
echo var n = new Array("', join($n,'","'), '");';
echo '</script>';
?>
<code>
<pre>
<!DOCTYPE html>
<html><head><meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0,user-scalable=no"/>
<!-- Google Maps -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js? `enter code here`sensor=true"></script>
<script type="text/javascript" charset="utf-8" src="cordova-1.6.0.js">
</script>
<!-- program main -->
<script type="text/javascript">
var iterator=0;
markers=n;
var a=n.length;
function load() {
var map_div = document.getElementById("map_div");
//initial locator
navigator.geolocation.watchPosition(onSuccess, onError, { frequency: 3000 `enter code here`});
// decide location
function onSuccess(position){
//fetching latlng from GPS
var latlng = new google.maps.LatLng(position.coords.latitude,
`position.coords.longitude);
// display map
var gmap = new google.maps.Map(
map_div, {
zoom:16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//drop the marker
function drop() {
for (var i = 0; i < a; i++) {
setTimeout(function() {
}, i * 200);
}
}
//decode address to latlng
//pass address data from PHP
for(var i in n){
var address=n;
geocoder=new google.maps.Geocoder();
geocoder.geocode({'address':address},function(results,status){
if(status==google.maps.GeocoderStatus.OK){
//alert("AAA");
address=results(i).geometry.location;
function addMarker() { markers.push(new google.maps.Marker({
postion:results(i).geometry.location,
map:gmap,
animation:google.map.animation.DROP
//iterater++;
}));
//itertor++;
}
//markerNearBy.setMap(map);
}else{
alert("Geocode was not sucessful for the following reason:"+status);
}
});
}
}
}
function onError(error) {
alert('code: '+ error.code+ '\n'
+'message: ' + error.message + '\n');
}
</script>
</head>
<body onLoad="load()">
<!-- Map Display place -->
<div id="map_div" style="width:320px; height:480px;"></div>
</body>
</html>
<code>
Your code doesn't look well-formed. You have the "addMarker" function defined inside your "for" loop. Also, it's not getting called anywhere.
Take a look at the sample code Google provides for working with markers and overlays and try to emulate it. The sample only uses one marker, but you can simply iterate through your results. You've got the right intentions by adding your Marker objects to an array, and setting your map object to the map property of the Marker, but you will need to format/restructure your code first or it will not work.
Sample code:
https://developers.google.com/maps/documentation/javascript/overlays#RemovingOverlays