Можно ли написать собственный текст в Google Maps API v3?

Можно ли написать собственный текст в Google Maps API v3 рядом с маркером, или я могу использовать для этого только информационное окно?


person user198003    schedule 17.10.2010    source источник
comment
смотри это не возможно... вроде единственный выход это создать прозрачное окно InfoBox и написать в нем текст... скажи мне, если я ошибаюсь?   -  person user198003    schedule 18.10.2010
comment
Могу ли я добавить пользовательский текст (скорее всего, слово) на маркер в API статической карты Google Map ..?   -  person Jay Modi    schedule 03.02.2015


Ответы (6)


Чтобы отобразить пользовательский текст, вам необходимо создать пользовательский оверлей. Ниже приведен пример, адаптированный из официальной документации Google. Вы также можете использовать эту библиотеку для получения дополнительных " стильные информационные окна

<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>

person Michal    schedule 17.10.2010
comment
Это круто. Я чешу затылок, удивляясь, почему Google не включил это по умолчанию. - person Shane Stillwell; 24.11.2011
comment
Есть ли способ изменить размер текста метки? Добавление «размера шрифта: 30 пикселей» в блок стилей, похоже, не работает. - person Turtles Are Cute; 10.11.2013
comment
Работает как шарм! Отличный ответ! - person Kumar Vaibhav; 07.06.2014
comment
Это сработало отлично, за исключением того, что мне пришлось добавить div.style.position = 'absolute';, чтобы текст отображался в правильном положении. - person John Doe; 02.09.2016
comment
Работает отлично! Но есть ли простой способ расположить блок в нижнем центре, а не в верхнем левом углу? - person mathkid91; 17.02.2017

Безусловно, самый простой способ добавить наложение текста — использовать класс MapLabel из https://github.com/googlemaps/js-map-label

var mapLabel = new MapLabel({
  text: 'Test',
  position: new google.maps.LatLng(50,50),
  map: map,
  fontSize: 20,
  align: 'right'
});
person Jake Wilson    schedule 18.11.2012
comment
Я получаю сообщение об ошибке Uncaught ReferenceError: MapLabel не определен, как добавить служебную библиотеку? - person muffin; 10.10.2014
comment
Но вам нужно использовать этот http://google-maps-utility-library-v3.googlecode.com/svn/trunk/maplabel/src/maplabel.js - person Legionar; 10.08.2015
comment
@Legionar Вышеуказанные 2 ссылки не работают. пожалуйста, проверьте ссылку, которую вы предоставили здесь - person codelearner; 22.04.2016
comment
@codelearner Обе ссылки работают, также вы можете перейти на одну папку вверх, и вы увидите содержимое, а также оба файла - google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/ и google-maps-utility-library-v3.googlecode.com/svn/trunk/ - person Legionar; 22.04.2016
comment
@Legionar Ссылки определенно НЕ работают. Вы уверены, что им не требуются разрешения или что-то в этом роде? - person Rob Evans; 03.06.2016
comment
Работающая ссылка: github.com/ googlemaps/js-map-label/blob/gh-pages/src/ - person Rob Evans; 03.06.2016
comment
@RobEvans На прошлой неделе он все еще работал, но Google переместил источники в code.google.com/p/google-maps-utility-library-v3/source/browse/ просто используйте Google, и вы его найдете. теперь URL-адрес JS: code.google.com/p/google-maps-utility-library-v3/source/browse/ - person Legionar; 03.06.2016
comment
code.google.com/p/google-maps-utility-library -v3 говорит, что мы переехали на GitHub! - person David Bridgeland; 07.11.2016

Чтобы добавить пользовательский текст на карты Google, вы можете использовать маркер с пустым пикселем для значка:

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',
    },
});

Здесь перечислены параметры стиля

person Felix Turner    schedule 07.02.2020

Если текст статичен, вы можете использовать маркер и изображение:

var label = new google.maps.Marker({
    position: new google.maps.LatLng(50,50),
    map: map,
    icon: "/images/mytextasanimage.png"
});
person user4269131    schedule 19.11.2014

В последнем (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);
}
person stephenhouser    schedule 14.05.2018

Вот рабочий код:

#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>
person Ajith Tolroy    schedule 08.09.2018