Algernop K. Algernop K. - 6 months ago 37
Ajax Question

Replace long/lat on Google maps via AJAX

I have this map script from Google Maps implemented on my site. What I'd like to do is I'd like to replace the latitude and longitude numbers (

lat
&
lng
) with numbers I've fetched from an API via AJAX.

The variables containing the longitude numbers and latitude numbers are returned like:
data.mondayLat
&
data.mondayLong
via the successfunction of AJAX. I've tried just replacing the default map setting
00.0000000
with
data.mondayLat
, but that isn't working. How do I make those variables continuously replace the default numbers in the map function, and make the map update each time I fetch data via AJAX?

<script>
function initMap() {
/* The following variable data I want to replace with the AJAX responde numbers */
var myLatLng = {lat: 00.0000000, lng: 00.0000000};

var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 13,
center: myLatLng
});

var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Today we are here'
});
}
google.maps.event.addDomListener(window, 'load', initMap);
</script>

<div id="googleMap" style="width:500px;height:380px;float:lefT;margin-left:20px;border:3px solid;"></div>

Answer

Your AJAX request is asynchronous. Call the initMap routine in the AJAX success function once you have the results (data.mondayLat and data.mondayLong exist).