【问题标题】:Google Maps Marker Data谷歌地图标记数据
【发布时间】:2011-11-15 16:15:47
【问题描述】:

我目前正在对服务器进行 ajax 调用,以获取要在谷歌地图上显示的纬度/经度列表。我还为每个标记附加了一个“点击”事件。诀窍是我需要能够将一些额外的数据存储到标记中,以了解我正在处理的 ID(来自数据库),以便稍后将其匹配回数据库。我正在使用 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);
    }
});

【问题讨论】:

    标签: javascript jquery ajax google-maps


    【解决方案1】:

    哈!我想到了。 “这个”做到了!

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

    【讨论】:

      【解决方案2】:

      我认为您的方法是正确的,只是事件处理程序不正确。在你的处理程序中

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

      mark 参数不是您所期望的标记,而是MouseEvent (see 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);
          }
      },
      

      【讨论】:

      • BTW- 在这种情况下,不再需要使用自定义数据扩展标记对象,您可以使用 data[i].ID 将第二个参数传递给 attachClickEvent 函数
      • 这应该是公认的答案。它提供了一种干净的方法,不涉及将未使用的参数留在处理程序中,正如 OP 自己的回答所暗示的那样。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-29
      • 2018-04-19
      • 2011-08-24
      • 1970-01-01
      相关资源
      最近更新 更多