Javascript 将 ID 添加到谷歌地图标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2564320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding ID's to google map markers
提问by Nick
I have a script that loops and adds markers one at a time.
我有一个循环并一次添加一个标记的脚本。
I am trying to get the current marker to have an info window and and only have 5 markers on a map at a time (4 without info windows and 1 with)
我试图让当前标记有一个信息窗口,并且一次在地图上只有 5 个标记(4 个没有信息窗口,1 个有)
How would I add an id to each marker so that I can delete and close info windows as needed.
我将如何为每个标记添加一个 id,以便我可以根据需要删除和关闭信息窗口。
This is the function I am using to set the marker:
这是我用来设置标记的函数:
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);
}
});
}
}
}
回答by CrazyEnigma
JavaScript is a dynamic language. You could just add it to the object itself.
JavaScript 是一种动态语言。您可以将它添加到对象本身。
var marker = new google.maps.Marker(markerOptions);
marker.metadata = {type: "point", id: 1};
Also, because all v3 objects extend MVCObject(). You can use:
此外,因为所有 v3 对象都扩展了MVCObject(). 您可以使用:
marker.setValues({type: "point", id: 1});
// or
marker.set("type", "point");
marker.set("id", 1);
var val = marker.get("id");
回答by zen.c
Just adding another solution that works for me.. You can simply append it in the marker options:
只需添加另一个对我有用的解决方案..您可以简单地将其附加到标记选项中:
var marker = new google.maps.Marker({
map: map,
position: position,
// Custom Attributes / Data / Key-Values
store_id: id,
store_address: address,
store_type: type
});
And then retrieve them with:
然后使用以下命令检索它们:
marker.get('store_id');
marker.get('store_address');
marker.get('store_type');
回答by whalesalad
I have a simple Locationclass that I use to handle all of my marker-related things. I'll paste my code below for you to take a gander at.
我有一个简单的Location类,用于处理所有与标记相关的事情。我将在下面粘贴我的代码供您查看。
The last line(s) is what actually creates the marker objects. It loops through some JSON of my locations, which look something like this:
最后一行是实际创建标记对象的内容。它遍历我的位置的一些 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"}
Here is the code:
这是代码:
If you look at the target()method in my Location class, you'll see that I keep references to the infowindow's and can simply open()and close()them because of a reference.
如果您查看target()我的 Location 类中的方法,您会发现我保留了对信息窗口的引用,open()并且close()由于引用而可以简单地和它们。
See a live demo: http://ww1.arbesko.com/en/locator/(type in a Swedish city, like stockholm, and hit enter)
观看现场演示: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();
};
回答by bdl
Why not use an cache that stores each marker object and references an ID?
为什么不使用一个缓存来存储每个标记对象并引用一个 ID?
var markerCache= {};
var idGen= 0;
function codeAddress(addr, contentStr){
// create marker
// store
markerCache[idGen++]= marker;
}
Edit: of course this relies on a numeric index system that doesn't offer a length property like an array. You could of course prototype the Object object and create a length, etc for just such a thing. OTOH, generating a unique ID value (MD5, etc) of each address might be the way to go.
编辑:当然,这依赖于不提供像数组那样的长度属性的数字索引系统。您当然可以为 Object 对象创建原型并为这样的事情创建长度等。OTOH,为每个地址生成唯一的 ID 值(MD5 等)可能是要走的路。
回答by bfg9k
Marker already has unique id
标记已具有唯一 ID
marker.__gm_id

