I am using Google Maps API v3. My script works fine and shows a car icon as long as
the marker is undefined. But when I update long lat in the database and the ajax function returns a new long lat via json, marker.setPosition(newLatLng) makes the marker disappear…
Please, help me out, what is the problem? Here is my code:
$(document).ready(function () {
var map;
var marker;
function initialize() {
var myLatlng = new google.maps.LatLng(<?php echo $c_lat; ?>, <?php echo $c_long; ?>);
var myOptions = {
zoom: 19,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('driver_loc'), myOptions);
}
function getLongLat(){
$.ajax({
type: "POST",
url: "config/getLongLat.php?id=<?php echo $driverId; ?>",
dataType: "json",
success: function(data)
{
var lat=data.lat; //returns new lat via db
var lon=data.lon;
// alert(lat);
var newLatLng = new google.maps.LatLng(lat, lon);
if (marker != undefined)
marker.setPosition(newLatLng);
else
marker = new google.maps.Marker({
position: newLatLng,
map: map,
icon: 'images/car.png',
animation: google.maps.Animation.DROP,
draggable: true
});
}
});
console.log(marker);
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
// google.maps.event.addDomListener(window, 'load', callPosition);
window.setInterval(function(){
getLongLat();
}, 6326);
});
A good practice is to use parseFloat method for json data. A new position can be outside of current view port. To handle it, just use map.setCenter([new_position]) method. You can also change zoom level with map.setZoom([zoom_level]).
In your case: