google maps move marker with lat/lng from ajax success returned data
Trying to move marker/map on interval with lat/long coords from sql db.
function initialize() {
var myLatLng = new google.maps.LatLng(41,14);
var myOptions = {
zoom: 16,
center: myLatLng,
scrollwheel: false,
panControl: true,
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true,
mapTypeId: google.maps.MapTypeId.SATELLITE,
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
marker = new google.maps.Marker({
position: myLatLng,
map: map,
draggable: false
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function getCoords() {
$.ajax({
url: "../ajaxscript.php",
type: "POST",
data: {
foo : "bar"
},
dataType: "text",
success: function(returnedData) {
alert(returnedData);
moveMarkerMap(returnedData);
}
});
}
function moveMarkerMap(newCoords) {
var newLatLang = new google.maps.LatLng(newCoords);
map.panTo(newLatLang);
marker.setPosition(newLatLang);
}
window.setInterval(getCoords, 5000);
Setting the new google.maps.LatLng(14,41) in moveMarkerMap() will move it, and the returnedData shows in alert() but marker won't move when used with moveMarkerMap()
The returned string from ajax is correct format; (9.624672,7.242244) as shown in alert() so not sure why its not working.
Solution 1:
The google.maps.LatLng constructor takes two numbers for arguments. This won't work:
var newLatLang = new google.maps.LatLng(newCoords);
You need to convert newCoords into two numbers.
Convert String to latlng google maps
Convert “[52.43242, 4.43242]” to google LatLng
How do I get a pin on Google Maps using location from a variable?