2011-04-28 52 views
4

我開始爲自己的Google地圖單獨列出我的標記,但很快意識到這是效率低下的 。我試圖創建一個數組來把標記放到我的地圖上,但它沒有顯示任何東西,你能看到我出錯的地方嗎?與Google Maps API的標記陣列拼搏

function initialize() { 
     var latlng = new google.maps.LatLng(52.474, -1.868); 

     var myOptions = { 
      zoom: 11, 
      center: latlng, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     }; 

     var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
     var image = 'i/hotel-map-pin.png'; 

     var hotels = [ 
      ['ibis Birmingham Airport', 52.452656, -1.730548, 4], 
      ['ETAP Birmingham Airport', 52.452527, -1.731644, 3], 
      ['ibis Birmingham City Centre', 52.475162, -1.897208, 2] 
     ]; 

     for (var i = 0; i < hotels.length; i++) { 
      var marker = new google.maps.Marker({ 
       position: hotels[1], 
       map: map, 
       icon: image, 
       title: hotels[0], 
       zIndex: hotels[2] 
      }); 
     } 
    } 

謝謝。

回答

4

在你的循環要訪問的酒店陣列以固定的索引(1,0 & 2),而不是在索引數組元素I:

for (var i = 0; i < hotels.length; i++) { 
     var hotel = hotels [i] 
     var marker = new google.maps.Marker({ 
      position: new google.maps.LatLng (hotel[1], hotel[2]), 
      map: map, 
      icon: image, 
      title: hotel[0], 
      zIndex: hotel[3] 
     }); 
    } 

Here是工作示例與修復。

+0

當然 - 我是一個塗料!謝謝。 – DarrylGodden 2011-04-28 13:45:32

+0

@Gogster沒問題。這是一個容易犯的錯誤。 – RedBlueThing 2011-04-28 23:57:13

+0

爲什麼不使用foreach(酒店作爲酒店)讓您的生活更輕鬆? – mydoglixu 2014-11-20 03:35:15

4

這裏就是你沒有正確訪問您的酒店陣列的JSFiddle Demo:

第一。對於lat和lng,標題hotels[i][1]hotels[i][2]應該是hotels[i][0],對於z-index應該是hotels[i][3]。其次,位置以lat和lng爲參數的google.maps.LatLng對象。

function initialize() { 
    var latlng = new google.maps.LatLng(52.474, -1.868); 

    var myOptions = { 
     zoom: 11, 
     center: latlng, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 

    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
    var image = 'i/hotel-map-pin.png'; 

    var hotels = [ 
     ['ibis Birmingham Airport', 52.452656, -1.730548, 4], 
     ['ETAP Birmingham Airport', 52.452527, -1.731644, 3], 
     ['ibis Birmingham City Centre', 52.475162, -1.897208, 2] 
     ]; 

    for (var i = 0; i < hotels.length; i++) { 
     var marker = new google.maps.Marker({ 
      position: new google.maps.LatLng(hotels[i][1], hotels[i][2]), 
      map: map, 
      // icon: image, 
      title: hotels[i][0], 
      zIndex: hotels[i][3] 
     }); 
    } 
} 

window.onload = initialize; 
+0

我註釋了jsfiddle的圖標 – kjy112 2011-04-28 13:39:33

+0

@ Kyj112 +1你用相同的答案將我打敗了約30秒; – RedBlueThing 2011-04-28 23:09:00

+0

@RedBlueThing oh hehe +1感謝Guru。你的確是,資歷,谷歌地圖科目/弓 – kjy112 2011-04-28 23:20:59