Question

We have a Google map on our website. We want to update latitude and longitude every 5 seconds (Call from MySQL) and change the marker place on the map, while the MAP or page don't reload with it. Our JAVASCRIPT code is:

var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
  zoom: 4,
  center: myLatlng,
  mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

// To add the marker to the map, use the 'map' property
var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title:"Hello World!"
});
Was it helpful?

Solution

You have to use an AJAX call to a backend script that will return something like a JSON string with new marker data.

jQuery code:

setInterval(function () {

    $.post('your-file.php', { }, function (r) {
        var result = eval('(' + r + ')');

        var newLatLng = new google.maps.LatLng(result.latitude, result.longitude);

        marker.setMap(null); 

        /* Recreate the marker here or update coordinates from result.latitude and result.longitude */
        });
}, 5000);

And this is your-file.php:

/* MySQL Query here */

echo json_encode('latitude' => $latitude, 'longitude' => $longitude);

Using marker.setMap(null) you can remove the marker from your map and then create it again with the correct coordinates otherwise just use marker.setPosition(newLatLng);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top