2016-11-26 55 views
1

我想在谷歌地圖上添加標記,當我得到AJAX標記數據,並調用initMap功能後地圖不會加載但經過寫警報()當我添加之前警報initMap函數,地圖加載。爲什麼我需要調用谷歌地圖API

這部作品,並顯示在地圖和標記:

$('#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); 
}); 

不加載地圖

$('#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); 
}); 

調用谷歌API:

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

爲什麼我需要提醒?

+0

,因爲你有你的selector.' $缺少的單引號('#ddlLatLog)。在此毫無疑問不起作用在所有'應該是'$( '#ddlLatLog')on' – NewToJS

+0

OPS我忘了,當複製代碼tanQ,但在我的項目有 '':d tanQ –

回答

2

沒有alert的地圖不加載的原因是jQuery.getJSONasync調用。所以,當你把alert,瀏覽器獲得的時間來完成ajax調用和響應回來被調用initMap之前。但在其他情況下,它不會發生,因爲您刪除alert。爲了克服這一點;你只需要成功處理程序中移動您的initMap(centermap, markermap);jQuery.getJSON如下:

$('#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); 
    }); 
}); 
+1

也不翼而飛單引號中選擇'$('#ddlLatLog).on'應該是'$( '#ddlLatLog')。on' – NewToJS

+0

哦...好抓。我只是複製粘貼的OP代碼沒有看到那個line..thanks @NewToJS。 – vijayP

+0

ops好現在罰款工作譚Q –