向谷歌地图标记添加ID

88

我有一个循环脚本,逐个添加标记。

我正在尝试使当前标记具有信息窗口,并且在地图上仅同时显示5个标记(4个没有信息窗口,1个有)

我该如何为每个标记添加ID,以便在需要时删除和关闭信息窗口。

这是我用来设置标记的函数:

function codeAddress(address, contentString) {

var infowindow = new google.maps.InfoWindow({
  content: contentString
});

if (geocoder) {

  geocoder.geocode( { 'address': address}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {

        map.setCenter(results[0].geometry.location);

       var marker = new google.maps.Marker({
          map: map, 
          position: results[0].geometry.location
       });

       infowindow.open(map,marker);

      } else {
       alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

}


这是一个只包含一个闭合大括号的 HTML 段落标签。
5个回答

206

JavaScript 是一种动态语言。你可以将它添加到对象本身。

var marker = new google.maps.Marker(markerOptions);
marker.metadata = {type: "point", id: 1};

另外,因为所有的v3对象都是扩展自MVCObject()。所以你可以使用:

marker.setValues({type: "point", id: 1});
// or
marker.set("type", "point");
marker.set("id", 1);
var val = marker.get("id");

13
我很好奇,如果你已经给标记分配了id,如何在地图画布之外访问这些标记。例如,$('#1').doSomething(); 应该怎么做? - willdanceforfun
@willdanceforfun 给标记添加点击事件并获取 this 上的信息:google.maps.event.addListener(yourMarker, 'click', function (event) { console.log(this); }); - Mayeenul Islam
3
以防有人正在寻找一个访问地图之外的id的解决方案。你可以通过将标记推入数组来跟踪它们。这样,你就可以通过迭代标记数组来访问标记。 - Matthäus Schwarzkogler

19

我只是想提供另一个对我有效的解决方案。您可以将其简单地附加在标记选项中:

var marker = new google.maps.Marker({
    map: map, 
    position: position,

    // Custom Attributes / Data / Key-Values
    store_id: id,
    store_address: address,
    store_type: type
});

然后使用以下方法检索它们:

marker.get('store_id');
marker.get('store_address');
marker.get('store_type');

这非常有帮助。没有一个例子提到过这点。适用于通过点击返回函数传递值的消费。 - cngodles

2

我有一个简单的位置(Location)类,用于处理所有与标记(Marker)相关的事情。下面是我的代码,供您查看。

最后一行(或几行)实际上是创建标记对象的代码。它循环遍历我的位置(JSON格式),看起来像这样:

{"locationID":"98","name":"Bergqvist Järn","note":null,"type":"retail","address":"Smidesvägen 3","zipcode":"69633","city":"Askersund","country":"Sverige","phone":"0583-120 35","fax":null,"email":null,"url":"www.bergqvist-jb.com","lat":"58.891079","lng":"14.917371","contact":null,"rating":"0","distance":"45.666885421019"}

这里是代码:

如果您查看我的 Location 类中的 target() 方法,您会发现我保留了指向信息窗口的引用,并且可以通过引用轻松地 open()close() 它们。

可查看在线演示:http://ww1.arbesko.com/en/locator/(输入瑞典城市名称,例如斯德哥尔摩,然后按回车键)

var Location = function() {
    var self = this,
        args = arguments;

    self.init.apply(self, args);
};

Location.prototype = {
    init: function(location, map) {
        var self = this;

        for (f in location) { self[f] = location[f]; }

        self.map = map;
        self.id = self.locationID;

        var ratings = ['bronze', 'silver', 'gold'],
            random = Math.floor(3*Math.random());

        self.rating_class = 'blue';

        // this is the marker point
        self.point = new google.maps.LatLng(parseFloat(self.lat), parseFloat(self.lng));
        locator.bounds.extend(self.point);

        // Create the marker for placement on the map
        self.marker = new google.maps.Marker({
            position: self.point,
            title: self.name,
            icon: new google.maps.MarkerImage('/wp-content/themes/arbesko/img/locator/'+self.rating_class+'SmallMarker.png'),
            shadow: new google.maps.MarkerImage(
                                        '/wp-content/themes/arbesko/img/locator/smallMarkerShadow.png',
                                        new google.maps.Size(52, 18),
                                        new google.maps.Point(0, 0),
                                        new google.maps.Point(19, 14)
                                    )
        });

        google.maps.event.addListener(self.marker, 'click', function() {
            self.target('map');
        });

        google.maps.event.addListener(self.marker, 'mouseover', function() {
            self.sidebarItem().mouseover();
        });

        google.maps.event.addListener(self.marker, 'mouseout', function() {
            self.sidebarItem().mouseout();
        });

        var infocontent = Array(
            '<div class="locationInfo">',
                '<span class="locName br">'+self.name+'</span>',
                '<span class="locAddress br">',
                    self.address+'<br/>'+self.zipcode+' '+self.city+' '+self.country,
                '</span>',
                '<span class="locContact br">'
        );

        if (self.phone) {
            infocontent.push('<span class="item br locPhone">'+self.phone+'</span>');
        }

        if (self.url) {
            infocontent.push('<span class="item br locURL"><a href="http://'+self.url+'">'+self.url+'</a></span>');
        }

        if (self.email) {
            infocontent.push('<span class="item br locEmail"><a href="mailto:'+self.email+'">Email</a></span>');
        }

        // Add in the lat/long
        infocontent.push('</span>');

        infocontent.push('<span class="item br locPosition"><strong>Lat:</strong> '+self.lat+'<br/><strong>Lng:</strong> '+self.lng+'</span>');

        // Create the infowindow for placement on the map, when a marker is clicked
        self.infowindow = new google.maps.InfoWindow({
            content: infocontent.join(""),
            position: self.point,
            pixelOffset: new google.maps.Size(0, -15) // Offset the infowindow by 15px to the top
        });

    },

    // Append the marker to the map
    addToMap: function() {
        var self = this;

        self.marker.setMap(self.map);
    },

    // Creates a sidebar module for the item, connected to the marker, etc..
    sidebarItem: function() {
        var self = this;

        if (self.sidebar) {
            return self.sidebar;
        }

        var li = $('<li/>').attr({ 'class': 'location', 'id': 'location-'+self.id }),
            name = $('<span/>').attr('class', 'locationName').html(self.name).appendTo(li),
            address = $('<span/>').attr('class', 'locationAddress').html(self.address+' <br/> '+self.zipcode+' '+self.city+' '+self.country).appendTo(li);

        li.addClass(self.rating_class);

        li.bind('click', function(event) {
            self.target();
        });

        self.sidebar = li;

        return li;
    },

    // This will "target" the store. Center the map and zoom on it, as well as 
    target: function(type) {
        var self = this;

        if (locator.targeted) {
            locator.targeted.infowindow.close();
        }

        locator.targeted = this;

        if (type != 'map') {
            self.map.panTo(self.point);
            self.map.setZoom(14);
        };

        // Open the infowinfow
        self.infowindow.open(self.map);
    }
};

for (var i=0; i < locations.length; i++) {
    var location = new Location(locations[i], self.map);
    self.locations.push(location);

    // Add the sidebar item
    self.location_ul.append(location.sidebarItem());

    // Add the map!
    location.addToMap();
};

那完全没有回答问题。 - MrUpsidown

1

为什么不使用一个缓存来存储每个标记对象并引用一个ID呢?

var markerCache= {};
var idGen= 0;

function codeAddress(addr, contentStr){
    // create marker
    // store
    markerCache[idGen++]= marker;
}

编辑:当然,这依赖于一个数字索引系统,它不像数组那样提供长度属性。你当然可以将Object对象原型化并创建长度等内容,以适应这种情况。另一方面,对每个地址生成一个唯一的ID值(MD5等)可能是更好的选择。

-2

标记已经具有唯一的ID

marker.__gm_id

这些中我会使用的唯一解决方案。 - clime
4
双下划线和 gm 前缀应该提示您这是一个没有保证的私有变量。避免使用它。 - Lee Goddard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接