Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show label on custom icon image in google map api

I am now working on GoogleMap and trying to show label on custom icon image as below.

var image = {
        url: "{% static "img/perch_logo_blue.png" %}",
        size: new google.maps.Size(45,45),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(0,32),
        scaledSize: new google.maps.Size(20, 20)
    };

    var shape = {
        coords: [1, 1, 1, 20, 18, 20, 18, 1],
        type: 'poly'
    };

    for (var i = 0; i < perches.length; i++) {
        var perch = perches[i];
        var marker = new google.maps.Marker({
          position: {lat: perch[1], lng: perch[2]},
          map: map,
          icon: image,
          label: '5',
          title: perch[0]
        });
    }

The problem is that the label is not on icon, but beside of icon image as below.

enter image description here

So I hope to know how to show label with white color on blue icon image.

Please help me!!!

like image 632
Samuel Jansson Avatar asked Dec 13 '15 12:12

Samuel Jansson


1 Answers

The color(and e.g. fontSize and fontFamily) may be set via the label-property of the marker:

Example for a white 5:

label:{text:'5',color:'white'}

The position of the label may be set via the labelOrigin-property of the icon

It's not clear how the original image looks like, you'll need to play around a little bit to find the best value for the labelOrigin(it's expected to be a google.maps.Point ).

Demo:

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 20,
      center: {
        lat: 52.5498783,
        lng: 13.425209099999961
      }
    }),
    marker = new google.maps.Marker({
      position: map.getCenter(),
      map: map,
      icon: {
        url: 'http://i.imgur.com/YsKYfOw.png',
        size: new google.maps.Size(45, 45),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(0, 20),
        scaledSize: new google.maps.Size(20, 20),
        labelOrigin: new google.maps.Point(9, 8)
      },
      label: {
        text: '5',
        fontWeight: 'bold',
        fontSize: '12px',
        fontFamily: '"Courier New", Courier,Monospace',
        color: 'white'
      }
    });
}
html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?v=3&callback=initMap"></script>

Note: in your example the value of the anchor-property seems to be incorrect. I guess the tail of the marker should point to the desired location. When the end of the tail is in the bottom-left corner of the image, the anchor should be (0,scaledHeightOfTheImage)

like image 192
Dr.Molle Avatar answered Sep 30 '22 19:09

Dr.Molle