2011-09-12 58 views
3

我目前正在對服務器進行ajax調用以獲取要在谷歌地圖上顯示的經緯度列表。我還爲每個標記附加了一個「點擊」事件。訣竅是我需要能夠將一點額外的數據存儲到標記中,以便知道我正在處理的數據庫ID(因此我稍後將它與db匹配)。我正在使用Title屬性來顯示一些友好的信息。 AJAX,標記創建和點擊事件工作正常。什麼是正確的方式來存儲標記的額外數據?看到代碼在這裏:谷歌地圖標記數據

$.ajax({ 
    url: "/location/NearbyHotspots", 
    data: { 
     lat: marker.position.lat(), 
     lng: marker.position.lng(), 
     radius: 10 
    }, 
    datatype: "json", 
    type: "POST", 
    success: function (data, status, xhttp) { 
     for (var i = 0; i < data.length; i++) { 
      var loc = new google.maps.LatLng(data[i].Lat, data[i].Long); 
      var newmarker = new google.maps.Marker({ 
       position: loc, 
       draggable: false, 
       map: map, 
       title: data[i].Name 
      }); 

      // This doesn't seem to work 
      newmarker.hotspotid = data[i].ID; 
      google.maps.event.addListener(newmarker, "click", function(mark) { 
       alert(mark.hotspotid); 
      }); 
     } 
    }, 
    error: function (jqXHR, textStatus, errorThrown) { 
     alert(textStatus); 
    } 
}); 

回答

10

HA!我想到了。 「這個」做到了!

google.maps.event.addListener(newmarker, "click", function(mark) { 
    alert(this.hotspotid); 
}); 
8

我認爲你的方法是正確的,它只是事件處理程序是不正確的。在您的處理程序

function(mark) { 
    alert(mark.hotspotid); 
} 

mark參數不是一個標記,如您所願,但MouseEventsee the API reference for details)。

爲了解決這個問題,您需要使用閉包來傳遞標記的引用。循環複雜化 - 您不能僅僅使用對newmarker的引用,因爲它只會引用循環中的最後一個標記。有幾種不同的方法可以解決此問題,但最簡單的方法是將單擊事件附加到單獨的函數中:

success: function (data, status, xhttp) { 
    // define a function to attach the click event 
    function attachClickEvent(marker) { 
     google.maps.event.addListener(marker, "click", function() { 
      // the reference to the marker will be saved in the closure 
      alert(marker.hotspotid); 
     }); 
    } 
    for (var i = 0; i < data.length; i++) { 
     var loc = new google.maps.LatLng(data[i].Lat, data[i].Long); 
     var newmarker = new google.maps.Marker({ 
      position: loc, 
      draggable: false, 
      map: map, 
      title: data[i].Name 
     }); 

     newmarker.hotspotid = data[i].ID; 
     attachClickEvent(newmarker); 
    } 
}, 
+0

BTW-在這種情況下不再有需要延長與自定義數據的標記對象,則可以通過一個第二PARAM與數據的attachClickEvent功能[I] .ID –

+0

這應該被接受的回答。它提供了一個乾淨的方式,它不涉及在處理程序中留下未使用的參數,因爲OP自己的答案表明。 – tfrascaroli