Javascript 带有标签的 Google Maps API v3 标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11043587/
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
Google Maps API v3 marker with label
提问by krikara
I am new to JS and the Google API and I am trying to make multiple markers each with a label.
我是 JS 和 Google API 的新手,我正在尝试使用标签制作多个标记。
From little snippets I've been looking at, there was no simple way to attach a label to a marker in Google Maps API v3. Between Google and stackoverflow searches, everyone used a roundabout procedure that involved creating or editing the label class.
从我一直在查看的小片段来看,没有简单的方法可以将标签附加到 Google Maps API v3 中的标记。在 Google 和 stackoverflow 搜索之间,每个人都使用了一个涉及创建或编辑标签类的迂回过程。
I just want to figure out how to attach a label to each marker in a simple way since I am just starting to learn JS/ Google API v3.
我只是想弄清楚如何以简单的方式将标签附加到每个标记上,因为我刚刚开始学习 JS/Google API v3。
Thanks
谢谢
EDIT #3: Okay I finally figured out what was wrong and correctly implemented multiple markers with labels using Lilina's code. Apparently we both defined the var map differently and that itself makes both our codes unable to synchronize well.
编辑 #3:好的,我终于弄清楚出了什么问题,并使用 Lilina 的代码正确实现了带有标签的多个标记。显然,我们都以不同的方式定义了 var 映射,这本身使我们的代码无法很好地同步。
I have an additional question now that I am able to use labels for each marker. I want to be able to hide markers and their labels based on the zoom level that the user is at.
我现在有一个额外的问题,我可以为每个标记使用标签。我希望能够根据用户所在的缩放级别隐藏标记及其标签。
Google Maps API v3 - Different markers/labels on different zoom levels
回答by Tina CG Hoehr
I can't guarantee it's the simplest, but I like MarkerWithLabel. As shown in the basic example, CSS styles define the label's appearance and options in the JavaScript define the content and placement.
我不能保证它是最简单的,但我喜欢MarkerWithLabel。如基本示例所示,CSS 样式定义标签的外观,JavaScript 中的选项定义内容和位置。
.labels {
color: red;
background-color: white;
font-family: "Lucida Grande", "Arial", sans-serif;
font-size: 10px;
font-weight: bold;
text-align: center;
width: 60px;
border: 2px solid black;
white-space: nowrap;
}
JavaScript:
JavaScript:
var marker = new MarkerWithLabel({
position: homeLatLng,
draggable: true,
map: map,
labelContent: "5K",
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.75}
});
The only part that may be confusing is the labelAnchor. By default, the label's top left corner will line up to the marker pushpin's endpoint. Setting the labelAnchor's x-value to half the width defined in the CSS width property will center the label. You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50)
.
唯一可能令人困惑的部分是 labelAnchor。默认情况下,标签的左上角将与标记图钉的端点对齐。将 labelAnchor 的 x 值设置为 CSS width 属性中定义的宽度的一半将使标签居中。您可以使用锚点(如 )使标签浮动在标记图钉上方new google.maps.Point(22, 50)
。
In case access to the links above are blocked, I copied and pasted the packed sourceof MarkerWithLabel into this JSFiddle demo. I hope JSFiddle is allowed in China :|
如果访问上述链接被阻止,我将MarkerWithLabel的打包源复制并粘贴到此JSFiddle 演示中。我希望 JSFiddle 在china被允许:|
回答by Jonathan
In order to add a label to the map you need to create a custom overlay. The sample at http://blog.mridey.com/2009/09/label-overlay-example-for-google-maps.htmluses a custom class, Layer
, that inherits from OverlayView
(which inherits from MVCObject
) from the Google Maps API. He has a revised version (adds support for visibility, zIndex and a click event) which can be found here: http://blog.mridey.com/2011/05/label-overlay-example-for-google-maps.html
为了向地图添加标签,您需要创建自定义叠加层。http://blog.mridey.com/2009/09/label-overlay-example-for-google-maps.html 上的示例使用自定义类 ,该类Layer
继承自OverlayView
(继承自MVCObject
)Google Maps API。他有一个修订版(增加了对可见性、zIndex 和点击事件的支持),可以在这里找到:http: //blog.mridey.com/2011/05/label-overlay-example-for-google-maps.html
The following code is taken directly from Marc Ridey's Blog (the revised link above).
下面的代码直接取自 Marc Ridey 的博客(上面修改过的链接)。
Layer class
图层类
// Define the overlay, derived from google.maps.OverlayView
function Label(opt_options) {
// Initialization
this.setValues(opt_options);
// Label specific
var span = this.span_ = document.createElement('span');
span.style.cssText = 'position: relative; left: -50%; top: -8px; ' +
'white-space: nowrap; border: 1px solid blue; ' +
'padding: 2px; background-color: white';
var div = this.div_ = document.createElement('div');
div.appendChild(span);
div.style.cssText = 'position: absolute; display: none';
};
Label.prototype = new google.maps.OverlayView;
// Implement onAdd
Label.prototype.onAdd = function() {
var pane = this.getPanes().overlayImage;
pane.appendChild(this.div_);
// Ensures the label is redrawn if the text or position is changed.
var me = this;
this.listeners_ = [
google.maps.event.addListener(this, 'position_changed', function() { me.draw(); }),
google.maps.event.addListener(this, 'visible_changed', function() { me.draw(); }),
google.maps.event.addListener(this, 'clickable_changed', function() { me.draw(); }),
google.maps.event.addListener(this, 'text_changed', function() { me.draw(); }),
google.maps.event.addListener(this, 'zindex_changed', function() { me.draw(); }),
google.maps.event.addDomListener(this.div_, 'click', function() {
if (me.get('clickable')) {
google.maps.event.trigger(me, 'click');
}
})
];
};
// Implement onRemove
Label.prototype.onRemove = function() {
this.div_.parentNode.removeChild(this.div_);
// Label is removed from the map, stop updating its position/text.
for (var i = 0, I = this.listeners_.length; i < I; ++i) {
google.maps.event.removeListener(this.listeners_[i]);
}
};
// Implement draw
Label.prototype.draw = function() {
var projection = this.getProjection();
var position = projection.fromLatLngToDivPixel(this.get('position'));
var div = this.div_;
div.style.left = position.x + 'px';
div.style.top = position.y + 'px';
div.style.display = 'block';
this.span_.innerHTML = this.get('text').toString();
};
Usage
用法
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>
Label Overlay Example
</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="label.js"></script>
<script type="text/javascript">
var marker;
function initialize() {
var latLng = new google.maps.LatLng(40, -100);
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 5,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
marker = new google.maps.Marker({
position: latLng,
draggable: true,
zIndex: 1,
map: map,
optimized: false
});
var label = new Label({
map: map
});
label.bindTo('position', marker);
label.bindTo('text', marker, 'position');
label.bindTo('visible', marker);
label.bindTo('clickable', marker);
label.bindTo('zIndex', marker);
google.maps.event.addListener(marker, 'click', function() { alert('Marker has been clicked'); })
google.maps.event.addListener(label, 'click', function() { alert('Label has been clicked'); })
}
function showHideMarker() {
marker.setVisible(!marker.getVisible());
}
function pinUnpinMarker() {
var draggable = marker.getDraggable();
marker.setDraggable(!draggable);
marker.setClickable(!draggable);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="height: 200px; width: 200px"></div>
<button type="button" onclick="showHideMarker();">Show/Hide Marker</button>
<button type="button" onclick="pinUnpinMarker();">Pin/Unpin Marker</button>
</body>
</html>
回答by rohit verma
the above solutions wont work on ipad-2
上述解决方案不适用于 ipad-2
recently I had an safari browser crash issue while plotting the markers even if there are less number of markers. Initially I was using marker with label (markerwithlabel.js) library for plotting the marker , when i use google native marker it was working fine even with large number of markers but i want customized markers , so i refer the above solution given by jonathan but still the crashing issue is not resolved after doing lot of research i came to know about http://nickjohnson.com/b/google-maps-v3-how-to-quickly-add-many-markersthis blog and now my map search is working smoothly on ipad-2 :)
最近,即使标记数量较少,我在绘制标记时也遇到了 safari 浏览器崩溃问题。最初我使用带标签的标记(markerwithlabel.js)库来绘制标记,当我使用谷歌原生标记时,即使有大量标记,它也能正常工作,但我想要自定义标记,所以我参考了乔纳森给出的上述解决方案,但是在做了大量研究后,崩溃问题仍未解决,我开始了解http://nickjohnson.com/b/google-maps-v3-how-to-quickly-add-many-markers这个博客,现在我的地图搜索在 ipad-2 上运行顺利 :)