简体   繁体   English

带有标签的Google Maps API v3标记

[英]Google Maps API v3 marker with label

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. 从我一直关注的小片段开始,没有简单的方法将标签贴在Google Maps API v3中的标记上。 Between Google and stackoverflow searches, everyone used a roundabout procedure that involved creating or editing the label class. 在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. 编辑#3:好的,我终于找出了错误,并使用Lilina的代码正确地使用标签实现了多个标记。 Apparently we both defined the var map differently and that itself makes both our codes unable to synchronize well. 显然我们都以不同的方式定义了var map,这本身使得我们的代码无法很好地同步。

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 Google Maps API v3 - 不同缩放级别的不同标记/标签

I can't guarantee it's the simplest, but I like MarkerWithLabel . 我不能保证这是最简单的,但我喜欢MarkerWithLabel As shown in the basic example , CSS styles define the label's appearance and options in the JavaScript define the content and placement. 基本示例所示,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: "$425K",
   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. 唯一可能令人困惑的部分是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. 将labelAnchor的x值设置为CSS width属性中定义的宽度的一半将使标签居中。 You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50) . 您可以使用new google.maps.Point(22, 50)类的锚点使标签浮动在标记图钉上方。

In case access to the links above are blocked, I copied and pasted the packed source of MarkerWithLabel into this JSFiddle demo . 如果访问上面的链接被阻止,我将MarkerWithLabel的打包源复制并粘贴到这个JSFiddle演示中 I hope JSFiddle is allowed in China :| 我希望JSFiddle在中国被允许:|

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.html uses a custom class, Layer , that inherits from OverlayView (which inherits from MVCObject ) from the Google Maps API. http://blog.mridey.com/2009/09/label-overlay-example-for-google-maps.html上的示例使用了一个自定义类Layer ,它继承自Google的OverlayView (继承自MVCObject ) 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 他有一个修订版本(添加了对可见性,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的Blog(上面的修订链接)。

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>

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. 最近我有一个safari浏览器崩溃问题,同时绘制标记,即使标记数量较少。 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-markers this blog and now my map search is working smoothly on ipad-2 :) 最初我使用带有标签(markerwithlabel.js)库的标记来绘制标记,当我使用谷歌原生标记时,即使使用大量标记也能正常工作,但我想要自定义标记,所以我参考jonathan给出的上述解决方案但是经过大量的研究,我开始了解http://nickjohnson.com/b/google-maps-v3-how-to-quickly-add-many-markers这个博客,现在我的地图仍然没有解决崩溃的问题搜索在ipad-2上顺利运行:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM