Reputation: 59
Iv been looking for help on this but everything i have found hasnt helped me.
I am trying to find a solution that will allow me to plot the GPS coordinates of a moving object "live" on a Google Map.
The GPS coordinates of each object will constantly be updating into a MySQL database, and I'd like to know whether it is possible to read each updated coordinate, maybe once every couple of seconds, and re-plot the marker coordinates on the Google Map, without the user having to refresh the page. Can this be done, or is it too complicated to do using Google Maps' API
Thanks in advance.
Edit > My Current Code.
<?php
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM `gps`";
$result=mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$_SESSION['x']=$row['x'];
$_SESSION['y']=$row['y'];
$_SESSION['driver']=$row['driver'];
$_SESSION['callsign']=$row['username'];
}?>
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Live Viewer</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function initialize() {
var myLatlng = new google.maps.LatLng(<?php echo $_SESSION['x'].",".$_SESSION['y']; ?>);
var mapOptions = {
zoom: 11,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: '<?php echo $_SESSION{'']; ?>'
});
}
function movemarker( map, marker ) {
marker.setPosition( myLatlng );
map.panTo( myLatlng );
};
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
Upvotes: 0
Views: 3644
Reputation: 133
Just setup a setInterval()
with an anonymous function that calls an Ajax request which retrieves the coordinates.
Then it's just a matter of updating the correct marker.
Something along the line of
setInterval(function(){
jQuery.getJSON('/getmarker.php?id=1234', function(data){
updateMarker(marker, data.lat, data.lng);
});
}, 5000);
Ofcourse you don't have to use jQuery for the ajax stuff, but it sure makes it easier...
Upvotes: 1
Reputation: 41968
This has nothing to do with the Google Maps API on its own. What you have to do is create an 'API-like' endpoint on your site that returns the updated coordinate(s), for example as a JSON string, and then use setTimeout
on the client side to frequently retrieve this endpoint's URL using Ajax/XHR. You can then parse it and apply it to the Google Maps instance.
How to actually develop this depends entirely on your frontend and backend choices, which JS library you use etc. etc.
Upvotes: 0