2017-04-19 94 views
0

我有一個JSON數據,其中包含城市的緯度和長度值。我需要將它放在Google地圖上並在其上放置標記。這是我的代碼:谷歌地圖上的設置標記不起作用

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> 
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 

<div id = "map"> 
    <script type="text/javascript"> 
    var map; 
    function init(){ 
     var options = { 
     zoom:11, 
     center : new google.maps.LatLng(37.542571,-121.993037) 
     }; 
     map = new google.maps.Map(document.getElementById("map"),options); 
    }; 
    var jsonData = { 
     "locations": 
     { 
      "location": 
      [ 
       { 
       "id": "0001", 
       "type": "RetailLocation", 
       "address": "Fremont, CA 94538", 
       "latitude":37.542571, 
       "longitude":-121.993037, 
       "$revenue": 10000000 
       }, 
       { 
       "id": "0002", 
       "type": "RetailLocation", 
       "address": "Newark, CA", 
       "latitude": 37.525400, 
       "longitude":-122.037764, 
       "$revenue": 3000000 
       }, 
       { 
       "id": "0003", 
       "type": "RetailLocation", 
       "address": "4100-4198 Pleiades Pl,Union City, CA 94587", 
       "latitude": 37.587546, 
       "longitude":-122.066716, 
       "$revenue": 120000000 
       }, 
       // ... 
      ] 
     } 
    }; 

    $(document).ready(function(){ 
     $.each(jsonData.locations.location,function(key,json){ 
     var latLng = new google.maps.LatLng(json.latitude,json.longitude); 

     var marker = new google.maps.Marker({ 
      position: latLng 
     }); 
     marker.setMap(map); 
     }); 
    }); 
    </script> 
</div> 

我試圖調試該問題。我從每個循環中獲取緯度和長度值。但是,當我嘗試使用標記將其放置在地圖上時,它不會顯示出來。有人能幫我嗎?

+2

下面是一個小提琴工作代碼注意CSS,並放置內初始化標誌代碼,並且回調= init添加到腳本SRC –

+1

或者,也有這個https://jsfiddle.net/81zteyuh/2/ - 再次,CSS添加,但在這種情況下,沒有添加回調,並且所有代碼都在文檔就緒中運行 - 並且不需要async/defer腳本 –

回答

0

您需要將您的回調添加到谷歌腳本中。文件。 OnReady不會觸發地圖準備事件。 https://jsfiddle.net/81zteyuh/1/ - -

<script async defer 
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"> 
</script> 
+0

在這種情況下,您還需要將'$ .each(jsonData.locations.location')移動到'init'而不是jquery的「文檔準備好」 - 並且'div id =「map」'需要一些身高!否則你最終會得到零高度的地圖! –