Arman Spr Arman Spr - 9 days ago 6
Javascript Question

Why do I need to write alert() after calling google map api

I want to add markers on the google map when I get ajax markers data and call

initMap
function after that map doesn't load but when I add an alert before
initMap
function, map is loaded.

this works and shows the map and markers:

$('#ddlLatLog').on("change", function() {
jQuery.getJSON('@Url.Action("GetLatLog", "MyTheme", new { area = "" })', {
id: $(this).find('option:selected').attr('Value')
},
function(jdata) {
markermap = jdata;
});
alert(markermap);
initMap(centermap, markermap);
});


don't load map

$('#ddlLatLog').on("change", function() {
jQuery.getJSON('@Url.Action("GetLatLog", "MyTheme", new { area = "" })', {
id: $(this).find('option:selected').attr('Value')
},
function(jdata) {
markermap = jdata;
});
// alert(markermap);
initMap(centermap, markermap);
});


call google api:

<script src="http://maps.google.com/maps/api/js?v=3.26&key=...callback=initMap" async defer></script>


why do I need the alert?

Answer

The reason for map not loading without alert is that jQuery.getJSON is an async call. So when you put alert, browser gets time to complete the ajax call and response comes back before initMap gets invoked. But in other case its not happening as you remove the alert. To overcome this; you just need to move your initMap(centermap, markermap); within success handler of jQuery.getJSON as follows:

$('#ddlLatLog').on("change", function() {
  jQuery.getJSON('@Url.Action("GetLatLog", "MyTheme", new { area = "" })', {
      id: $(this).find('option:selected').attr('Value')
    },
    function(jdata) {
      markermap = jdata;

      initMap(centermap, markermap);
    });
});
Comments