5

I have drawn polygon for each state over united states map. I wish to display a value (text/int) on top of it. I couldnt find any polygon options able to display text on top of polygon. What are the ways to do this?

var poly = new google.maps.Polygon({
                            clickable: true,
                            paths: pts,
                            strokeColor: '#000000',
                            strokeOpacity: 0.3,
                            strokeWeight: 1,
                            fillColor: colour,
                            fillOpacity: 0.8,
                            title: name
                        });
                        polys.push(poly);
                        poly.setMap(map);
user3469799
  • 219
  • 1
  • 3
  • 12
  • possible duplicate of [Google Maps Javascript API v3 Map Label and Polygons](http://stackoverflow.com/questions/12714031/google-maps-javascript-api-v3-map-label-and-polygons) – geocodezip Jan 25 '16 at 00:37
  • possible duplicate of [Google Maps get the center of coordinates (place label at center of polygon)](http://stackoverflow.com/questions/19956691/google-maps-get-the-center-of-coordinates-place-label-at-center-of-polygon) – geocodezip Jan 25 '16 at 00:39
  • I was looking for a better solution as compared to using a new library to display just a label @geocodezip – user3469799 Jan 25 '16 at 18:54

4 Answers4

3

I was looking for an easy implementation for that and I found this solutions. Hope can help someone:

  1. Create a marker at the position that you like to show the label (for example, in the middle of the polygon)
  2. In this marker, create the label.
  3. In this marker, use a 1px x 1px transparent image so the icon won't be displayed.
  4. You'll have the label above the polygon.

The code follows:

addMarkerAsLabel = async (position, map, title) => {
var marker = new this.props.google.Marker({
  position,
  map,
  draggable: false,
  label: {
    text: title,
    color: "#FFFFFF",
    textShadow: "2px 2px 2px #000000"
  },
  icon: {
    url: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAA1JREFUGFdjyHQt+g8ABFsCIF75EPIAAAAASUVORK5CYII="
  }
});
Peter VARGA
  • 4,780
  • 3
  • 39
  • 75
Rodrigo Xavier
  • 222
  • 2
  • 6
2

You can do this with the MapLabel Utility. Just set the location of the label and apply options through the object.

label: new MapLabel({
    text: result[index].name,
    position: 
       new google.maps.LatLng(object.lat, object.lng), // the lat/lng of location of the label.
    fontSize: 10,
    fontColor: #000,
    labelInBackground: true,
    strokeColor: #000,
    map: map   // The map object to place the label on
})
Tah
  • 1,526
  • 14
  • 22
  • 1
    The link doesn't work any more. Is this one? https://developers.google.com/maps/documentation/javascript/examples/marker-labels – Wilk Feb 17 '21 at 09:16
0

Polygon doesn't support this out of the box. What you can do is create a custom Label type by deriving from google.maps.OverlayView.

Then create a new Label, set its properties, and set its position to the center of your polygon. Once you do this, google maps api will update the label position if you happen to edit the polygon.

//for var polygon
var _label = new Label({ map: _options.map, text: _options.name, position: polygon.GetCenter(), color: _options.colour });
_label.bindTo("zoom", _options.map, "zoom");

The Label class. From a library I created a while back to manage spatial objects in google maps

define(
    ['gmaps'],
    function(gmaps) {

        // Define the overlay, derived from gmaps.OverlayView
        var label = function(options) {
            // Initialization
            this.setValues(options);

            var div = this.div_ = document.createElement('div');
            div.style.cssText = 'position: absolute; display: none; -webkit-transform: translateZ(0px); z-index:1000;';

            // Label specific
            var span = this.span_ = document.createElement('span');

            span.style.cssText = 'position: relative; left: -50%; top: -8px; display:block; filter:progid:DXImageTransform.Microsoft.Glow(Color=#333333, Strength=2); ' +
                'white-space: nowrap; border: none; color:' + this.get('color') + '; ' +
                'padding: 2px; z-index:1000; font-size:12px; ';

            if (this.get('shadowstyle') == undefined)
                span.style.cssText += 'text-shadow: -1px -1px 0px #111, 1px -1px 0px #111, -1px 1px 0px #111, 1px 1px 0px #111;';
            else
                span.style.cssText += this.get('shadowstyle');

            div.appendChild(span);
        };

        if (gmaps.OverlayView) {
            label.prototype = new gmaps.OverlayView();
        }

        // Implement onAdd
        label.prototype.onAdd = function() {
            var pane = this.getPanes().overlayLayer;
            pane.appendChild(this.div_);

            // Ensures the label is redrawn if the text or position is changed.
            var me = this;
            this.listeners_ = [
                gmaps.event.addListener(this, 'position_changed', function() { me.draw(); }),
                gmaps.event.addListener(this, 'text_changed', function() { me.draw(); })
            ];
        };

        // 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) {
                gmaps.event.removeListener(this.listeners_[i]);
            }
        };

        // Implement draw
        label.prototype.draw = function() {
            var projection = this.getProjection();
            var position = projection.fromLatLngToDivPixel(this.get('position'));
            var mapzoom = this.get('zoom');
            if (mapzoom == null) mapzoom = 16;

            var div = this.div_;

            if (mapzoom > 11) {
                div.style.left = position.x + 'px';
                div.style.top = position.y + 'px';
                div.style.display = 'block';
                this.span_.innerHTML = this.get('text').toString();
            } else {
                div.style.display = 'none';
            }
        };

        return label;
    }
);
Ro Lewis
  • 76
  • 7
-1

Try mouseOver. Not so sure though.

google.maps.event.addListener(polygon,"mouseover",function(){
this.setOptions({name: "title"});
});