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>
Related
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.
I am designing a system based on Google Maps and GPS. I am receiving the GPS information in my server every 10 seconds, and using a Java program it stores the latitude and longitude in a mysql database. Also, I'm making a website with google maps with the idea of tracking the device in real time.
The problem I'm having is that I need to query the mysql table every 10 seconds to retrieve the latitude+longitude, and the only way I have found so far is calling the php code over and over again, meaning with this:
<script>
setInterval(function(){
document.getElementById('google-map').contentDocument.location.reload(true);
},10000);
</script>
<iframe height="540" frameborder="0" scrolling="no" marginheight="10" marginwidth="0" width="100%" name="google-map" id="google-map"
src="google-map.php">
</iframe>
I am calling the php code under the name of google-map.php:
<?php
include_once("includes/checksession.php");
include_once("dbconn/dbconn.php");
$db = new runQuery();
$db->Dbconn(); //until now I just connect to my DB
$user_id = #$_SESSION['user_id'];
$sel_qry = "select * from Historico where Gps_Gpscol=\"$user_id\" order by Fecha desc limit 1";
$res_qry = mysql_query($sel_qry);
$num = mysql_num_rows($res_qry);
$row = mysql_fetch_assoc($res_qry);
$latitude = $row['Latitud'];
$lat_array = explode('.',$latitude);
$lat_deg = $lat_array[0];
$lat_array_new = explode(' ',$lat_array[0]);
$lat_deg = $lat_array_new[0];
$longitude = explode(".",$row['Longitud']);
$long_1 = explode(" ",$longitude[0]);
$long_deg = $long_1[0];
$long_min = $long_1[1];
$long_sec = $longitude[1];
$lat_new = $lat_deg.'.'.$lat_min.$lat_sec;
$long_new = $long_deg.'.'.$long_min.$long_sec;
[NOT RELEVANT CODE.. SUPRESED]
$nombre_format_lat = number_format($lat, 6, '.', ' ');
$nombre_format_long = number_format($long, 6, '.', ' ');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Kiwi</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
function LoadGmaps() {
var myLatlng = new google.maps.LatLng('-<?php echo $nombre_format_lat; ?>', '-<?php echo $nombre_format_long; ?>');
var myOptions = {
zoom: 17,
center: myLatlng,
disableDefaultUI: true,
panControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.DEFAULT
},
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
streetViewControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var image = {
url: 'img/kiwi.png',
scaledSize: new google.maps.Size(30,30)
}
var map = new google.maps.Map(document.getElementById("MyGmaps"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: '-<?php echo $row['Latitud']; ?> -<?php echo $row['Longitud']; ?>',
icon: image,
draggable: true
});
var myLatlng2 = new google.maps.LatLng('-34.607900','-58.426182');
var marker = new google.maps.Marker({
position: myLatlng2,
map: map,
title:"Pappo",
icon: image
});
}
</script>
</head>
<body onload="LoadGmaps()" onunload="GUnload()">
<!-- Maps DIV : you can move the code below to where you want the maps to be displayed -->
<div id="MyGmaps" style="width:100%;height:550px;border:1px solid #CECECE;"></div>
<!-- End of Maps DIV -->
</body>
</html>
The code is very long but it just query the database, extract the latitude and longitude, and converts it to a format I can actually use for google maps. Finally, the only variables I care are:
$nombre_format_lat and $nombre_format_long
But this way, the whole map is going to be reloaded every 10 seconds, which is very uncomfortable and I am planning to sell a service based on this website. I need to retrieve the latitude and longitude every 10 seconds but only reloading the marker! I tried to write the setInterval function inside the HTML code and calling the $nombre_format_lat and $nombre_format_long variables, but since I'm not fetching the database, those values will always be the same.
Any help would be much appreciated!
Thanks in advance.
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 trying to make a google map api with markers, which will show the latitude and longitude of some places.I am trying to do this with json file but it is not working..
here is my code ..
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cluster Map</title>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js" type="text/javascript"></script>
<script type="text/javascript">
var map;
var markers = [];
function initialize() {
geocoder = new google.maps.Geocoder();
var center = new google.maps.LatLng(43.474144,-112.03866);
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
markMultiple();
}
function markMap(latLng, content){
var marker = new google.maps.Marker({
position: latLng
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
markers.push(marker);
}
function markMultiple(){
$.parseJSON('test.json', function(data) {
$.each(data.markers, function(i, obj) {
var latLng = new google.maps.LatLng(obj.lat,obj.lng);
var content = obj.id + ':' + obj.lat + ',' + obj.lng;
markMap(latLng, content);
});
});
var markerCluster = new MarkerClusterer(map, markers);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-container">
<div id="map"></div>
</div>
</body>
please help me..
Engineer was right, you need to use $.getJSON method, $.parseJSON takes a JSON string, it doesn't load an external file.
getJSON: http://api.jquery.com/jQuery.getJSON/
parseJSON: http://api.jquery.com/jQuery.parseJSON/
I put your code in a jsFiddle and it is working with getJSON and an alternative test JSON file (you didn't provide the original test.json you're using).
$.getJSON('test.json', function(data) {
$.each(data.markers, function(i, obj) {
var latLng = new google.maps.LatLng(obj.lat,obj.lng);
var content = obj.id + ':' + obj.lat + ',' + obj.lng;
markMap(latLng, content);
});
});
http://jsfiddle.net/WYfjv/
If your code is not working maybe your JSON is not well formatted (try JSONLINT to test it). Also, if you are already improving, I would advise to use a normal for loop rather than $.each :)
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