是否可以在 Google Maps API v3 上编写自定义文本?

Posted

技术标签:

【中文标题】是否可以在 Google Maps API v3 上编写自定义文本?【英文标题】:Is it possible to write custom text on Google Maps API v3? 【发布时间】:2011-04-26 14:50:10 【问题描述】:

是否可以在标记旁边的 Google Maps API v3 上编写自定义文本,或者我可以仅使用信息窗口来执行此操作?

【问题讨论】:

看起来不可能...就像唯一的方法是创建透明的信息框窗口并在上面写文字...告诉我我是否错了? 我可以在谷歌地图静态地图 API 的标记上添加自定义文本(最有可能是一个词)吗? 【参考方案1】:

要向谷歌地图添加自定义文本,您可以使用带有空像素的标记作为图标:

new google.maps.Marker(
    position:  lat: 0, lng: 0 ,
    map: map,
    icon: '../res/img/empty.png',
    label: 
        color: '#FF0000',
        fontWeight: 'bold',
        text: 'Hello World',
        fontSize: '20px',
    ,
);

Style options are listed here

【讨论】:

如果没有其他人这样做,我将发布此解决方案。我认为这是最好的一个。愚蠢的是,现在没有标记就无法添加标签。他们出于某种原因在某个时候删除了标签类别。 我将我的图标设置为data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=,因为这样我就不需要保存空白图像文件了。它只是一个透明像素。【参考方案2】:

这是工作代码:

#map 
  height: 500px;

html, body 
  height: 100%;
  margin: 0;
  padding: 0;


<div id="content">
  <div id="map"></div>
  <div class="centered">
    <h1>Text Over Maps</h1>
  </div>
</div>

【讨论】:

【参考方案3】:

最新 (v3) API 建议使用 async defer 并在加载 Maps API 时使用回调。

<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>

要完成这项工作,您需要在定义 google 类时从初始化内部(或之后)定义覆盖类。否则你会得到google not defined 错误。

function initMap() 
    var map = new google.maps.Map(document.getElementById('map'), 
        center:  lat: 40, lng: -30 ,
        zoom: 3
    );

    TxtOverlay.prototype = new google.maps.OverlayView();
    var overlay = new TxtOverlay(new google.maps.LatLng(0, 0),
        "<div>Have a wonderful overlay day</div>", 
        "customCSSClass", 
        map);


...

//adapded from answer above
function TxtOverlay(pos, txt, cls, map) 
    // Now initialize all properties.
    this.pos = pos;
    this.txt_ = txt;
    this.cls_ = cls;
    this.map_ = map;

    // We define a property to hold the image's
    // div. We'll actually create this div
    // upon receipt of the add() method so we'll
    // leave it null for now.
    this.div_ = null;

    this.onAdd = function() 
        // Note: an overlay's receipt of onAdd() indicates that
        // the map's panes are now available for attaching
        // the overlay to the map via the DOM.

        // Create the DIV and set some basic attributes.
        var div = document.createElement('DIV');
        div.className = this.cls_;

        div.innerHTML = this.txt_;

        // Set the overlay's div_ property to this DIV
        this.div_ = div;
        var overlayProjection = this.getProjection();
        var position = overlayProjection.fromLatLngToDivPixel(this.pos);
        div.style.left = position.x + 'px';
        div.style.top = position.y + 'px';
        // We add an overlay to a map via one of the map's panes.

        var panes = this.getPanes();
        panes.floatPane.appendChild(div);
    

    this.draw = function() 
        var overlayProjection = this.getProjection();

        // Retrieve the southwest and northeast coordinates of this overlay
        // in latlngs and convert them to pixels coordinates.
        // We'll use these coordinates to resize the DIV.
        var position = overlayProjection.fromLatLngToDivPixel(this.pos);

        var div = this.div_;
        div.style.left = position.x + 'px';
        div.style.top = position.y + 'px';
    

    this.onRemove = function() 
        this.div_.parentNode.removeChild(this.div_);
        this.div_ = null;
    

    this.hide = function() 
            if (this.div_) 
                this.div_.style.visibility = "hidden";
            
        

    this.show = function() 
        if (this.div_) 
            this.div_.style.visibility = "visible";
        
    

    this.toggle = function() 
        if (this.div_) 
            if (this.div_.style.visibility == "hidden") 
                this.show();
             else 
                this.hide();
            
        
    

    this.toggleDOM = function() 
        if (this.getMap()) 
            this.setMap(null);
         else 
            this.setMap(this.map_);
        
    

    // Explicitly call setMap() on this overlay
    this.setMap(map);

【讨论】:

【参考方案4】:

到目前为止,添加文本叠加层最简单的方法是使用 https://github.com/googlemaps/js-map-label 中的 MapLabel

var mapLabel = new MapLabel(
  text: 'Test',
  position: new google.maps.LatLng(50,50),
  map: map,
  fontSize: 20,
  align: 'right'
);

【讨论】:

我收到错误“Uncaught ReferenceError: MapLabel is not defined”,如何添加实用程序库? &lt;script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"&gt;&lt;/script&gt; 但是你需要用这个http://google-maps-utility-library-v3.googlecode.com/svn/trunk/maplabel/src/maplabel.js @Legionar 以上 2 个链接无效。请检查您在此处提供的链接 @codelearner 两个链接都有效,你也可以上一个文件夹,你会看到内容和两个文件 - google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/… 和 google-maps-utility-library-v3.googlecode.com/svn/trunk/…【参考方案5】:

要显示自定义文本,您需要创建自定义叠加层。以下是改编自 Google 官方文档的示例。您还可以使用this library 获取更多“时尚”信息窗口

<html>

<head>
  <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
  </script>
  <script>
    //adapded from this example http://code.google.com/apis/maps/documentation/javascript/overlays.html#CustomOverlays
     //text overlays
    function TxtOverlay(pos, txt, cls, map) 

      // Now initialize all properties.
      this.pos = pos;
      this.txt_ = txt;
      this.cls_ = cls;
      this.map_ = map;

      // We define a property to hold the image's
      // div. We'll actually create this div
      // upon receipt of the add() method so we'll
      // leave it null for now.
      this.div_ = null;

      // Explicitly call setMap() on this overlay
      this.setMap(map);
    

    TxtOverlay.prototype = new google.maps.OverlayView();



    TxtOverlay.prototype.onAdd = function() 

      // Note: an overlay's receipt of onAdd() indicates that
      // the map's panes are now available for attaching
      // the overlay to the map via the DOM.

      // Create the DIV and set some basic attributes.
      var div = document.createElement('DIV');
      div.className = this.cls_;

      div.innerHTML = this.txt_;

      // Set the overlay's div_ property to this DIV
      this.div_ = div;
      var overlayProjection = this.getProjection();
      var position = overlayProjection.fromLatLngToDivPixel(this.pos);
      div.style.left = position.x + 'px';
      div.style.top = position.y + 'px';
      // We add an overlay to a map via one of the map's panes.

      var panes = this.getPanes();
      panes.floatPane.appendChild(div);
    
    TxtOverlay.prototype.draw = function() 


        var overlayProjection = this.getProjection();

        // Retrieve the southwest and northeast coordinates of this overlay
        // in latlngs and convert them to pixels coordinates.
        // We'll use these coordinates to resize the DIV.
        var position = overlayProjection.fromLatLngToDivPixel(this.pos);


        var div = this.div_;
        div.style.left = position.x + 'px';
        div.style.top = position.y + 'px';



      
      //Optional: helper methods for removing and toggling the text overlay.  
    TxtOverlay.prototype.onRemove = function() 
      this.div_.parentNode.removeChild(this.div_);
      this.div_ = null;
    
    TxtOverlay.prototype.hide = function() 
      if (this.div_) 
        this.div_.style.visibility = "hidden";
      
    

    TxtOverlay.prototype.show = function() 
      if (this.div_) 
        this.div_.style.visibility = "visible";
      
    

    TxtOverlay.prototype.toggle = function() 
      if (this.div_) 
        if (this.div_.style.visibility == "hidden") 
          this.show();
         else 
          this.hide();
        
      
    

    TxtOverlay.prototype.toggleDOM = function() 
      if (this.getMap()) 
        this.setMap(null);
       else 
        this.setMap(this.map_);
      
    




    var map;

    function init() 
      var latlng = new google.maps.LatLng(37.9069, -122.0792);
      var myOptions = 
        zoom: 4,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      ;
      map = new google.maps.Map(document.getElementById("map"), myOptions);

      var marker = new google.maps.Marker(
        position: latlng,
        map: map,
        title: "Hello World!"
      );

      customTxt = "<div>Blah blah sdfsddddddddddddddd ddddddddddddddddddddd<ul><li>Blah 1<li>blah 2 </ul></div>"
      txt = new TxtOverlay(latlng, customTxt, "customBox", map)

    
  </script>
  <style>
    .customBox 
      background: yellow;
      border: 1px solid black;
      position: absolute;
    
  </style>
</head>

<body onload="init()">
  <div id="map" style="width: 600px; height: 600px;">
  </div>
</body>

</html>

【讨论】:

这太棒了。我挠了挠头,想知道为什么 Google 默认不包含这个。 有没有办法改变标签文字大小?在样式块中添加 'font-size: 30px' 似乎不起作用。 像魅力一样工作!很好的答案! 效果很好,只是我必须添加 div.style.position = 'absolute'; 才能使文本出现在正确的位置。 效果很好!但是有没有一种简单的方法可以将框定位在底部中心而不是左上角?【参考方案6】:

如果文本是静态的,您可以使用标记和图像:

var label = new google.maps.Marker(
    position: new google.maps.LatLng(50,50),
    map: map,
    icon: "/images/mytextasanimage.png"
);

【讨论】:

以上是关于是否可以在 Google Maps API v3 上编写自定义文本?的主要内容,如果未能解决你的问题,请参考以下文章

Google Maps Api v3 - 查找最近的标记

Google Maps v3 - 防止 API 加载 Roboto 字体

Esri Feature Services和Google Maps API v3

在 Google Maps API v3 上显示我的位置

Google Maps API v3:未删除标记

使用 Google Maps API V3,确定标记是不是在 KML 图层边界内