51

How can I display a number in the marker on a google map? I want to do server side clustering and I need to display how many points the cluster represents.

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
User
  • 62,498
  • 72
  • 186
  • 247

11 Answers11

51
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=1|FE6256|000000'

Looks fine with 1-digit and 2-digit numbers

(from Mauro's link)

Jerome Jaglale
  • 1,863
  • 18
  • 22
23

Latest google js API has google.maps.MarkerLabel object.

So you can easily set text/styles for labels

var mIcon = {
  path: google.maps.SymbolPath.CIRCLE,
  fillOpacity: 1,
  fillColor: '#fff',
  strokeOpacity: 1,
  strokeWeight: 1,
  strokeColor: '#333',
  scale: 12
};

var gMarker = new google.maps.Marker({
  map: gmap,
  position: latLng,
  title: 'Number 123',
  icon: mIcon,
  label: {color: '#000', fontSize: '12px', fontWeight: '600',
    text: '123'}
});

jsfiddle

Valery Viktorovsky
  • 6,487
  • 3
  • 39
  • 47
  • If the points are very close to each other, for some reason the numbers display on top of each other. (rather than only showing one or the other with the others "stacked" behind) - the icon text layer is a layer above all of the icon backgrounds. – Ben in CA Jan 18 '20 at 16:48
20

Here are custom icons with the updated "visual refresh" style that you can generate quickly via a simple .vbs script. I also included a large pre-generated set that you can use immediately with multiple color options: https://github.com/Concept211/Google-Maps-Markers

Use the following format when linking to the GitHub-hosted image files:

https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_[color][character].png

color

red, black, blue, green, grey, orange, purple, white, yellow

character

A-Z, 1-100, !, @, $, +, -, =, (%23 = #), (%25 = %), (%26 = &), (blank = •)

Examples:

red1 https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_red1.png

blue2 https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_blue2.png

green3 https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_green3.png

Concept211
  • 1,066
  • 11
  • 11
17

Instead of use the default solution (http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=7|FF0000|000000), you can create these images as you wish, using JavaScript without any server-side code.

Google google.maps.Marker accepts Base64 for its icon property. With this we can create a valid Base64 from a SVG.

enter image description here

You can see the code to produce the same as this image in this Plunker: http://plnkr.co/edit/jep5mVN3DsVRgtlz1GGQ?p=preview

var markers = [
  [1002, -14.2350040, -51.9252800],
  [2000, -34.028249, 151.157507],
  [123, 39.0119020, -98.4842460],
  [50, 48.8566140, 2.3522220],
  [22, 38.7755940, -9.1353670],
  [12, 12.0733335, 52.8234367],
];

function initializeMaps() {
  var myLatLng = {
    lat: -25.363,
    lng: 131.044
  };

  var map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 4,
    center: myLatLng
  });

  var bounds = new google.maps.LatLngBounds();

  markers.forEach(function(point) {
    generateIcon(point[0], function(src) {
      var pos = new google.maps.LatLng(point[1], point[2]);

      bounds.extend(pos);

      new google.maps.Marker({
        position: pos,
        map: map,
        icon: src
      });
    });
  });

  map.fitBounds(bounds);
}

var generateIconCache = {};

function generateIcon(number, callback) {
  if (generateIconCache[number] !== undefined) {
    callback(generateIconCache[number]);
  }

  var fontSize = 16,
    imageWidth = imageHeight = 35;

  if (number >= 1000) {
    fontSize = 10;
    imageWidth = imageHeight = 55;
  } else if (number < 1000 && number > 100) {
    fontSize = 14;
    imageWidth = imageHeight = 45;
  }

  var svg = d3.select(document.createElement('div')).append('svg')
    .attr('viewBox', '0 0 54.4 54.4')
    .append('g')

  var circles = svg.append('circle')
    .attr('cx', '27.2')
    .attr('cy', '27.2')
    .attr('r', '21.2')
    .style('fill', '#2063C6');

  var path = svg.append('path')
    .attr('d', 'M27.2,0C12.2,0,0,12.2,0,27.2s12.2,27.2,27.2,27.2s27.2-12.2,27.2-27.2S42.2,0,27.2,0z M6,27.2 C6,15.5,15.5,6,27.2,6s21.2,9.5,21.2,21.2c0,11.7-9.5,21.2-21.2,21.2S6,38.9,6,27.2z')
    .attr('fill', '#FFFFFF');

  var text = svg.append('text')
    .attr('dx', 27)
    .attr('dy', 32)
    .attr('text-anchor', 'middle')
    .attr('style', 'font-size:' + fontSize + 'px; fill: #FFFFFF; font-family: Arial, Verdana; font-weight: bold')
    .text(number);

  var svgNode = svg.node().parentNode.cloneNode(true),
    image = new Image();

  d3.select(svgNode).select('clippath').remove();

  var xmlSource = (new XMLSerializer()).serializeToString(svgNode);

  image.onload = (function(imageWidth, imageHeight) {
    var canvas = document.createElement('canvas'),
      context = canvas.getContext('2d'),
      dataURL;

    d3.select(canvas)
      .attr('width', imageWidth)
      .attr('height', imageHeight);

    context.drawImage(image, 0, 0, imageWidth, imageHeight);

    dataURL = canvas.toDataURL();
    generateIconCache[number] = dataURL;

    callback(dataURL);
  }).bind(this, imageWidth, imageHeight);

  image.src = 'data:image/svg+xml;base64,' + btoa(encodeURIComponent(xmlSource).replace(/%([0-9A-F]{2})/g, function(match, p1) {
    return String.fromCharCode('0x' + p1);
  }));
}

initializeMaps();
#map_canvas {
  width: 100%;
  height: 300px;
}
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
    
  </head>

  <body>
    <div id="map_canvas"></div>
  </body>
  
  <script src="script.js"></script>

</html>

In this demo I create the SVG using D3.js, then transformed SVG to Canvas, so I can resize the image as I want and after that I get Base64 using canvas' toDataURL method.

All this demo was based on my fellow @thiago-mata's code. Kudos for him.

Estevão Lucas
  • 4,440
  • 34
  • 37
  • 1
    This demo is working fine in chrome but it is not working on firefox the icons are not being generated.. why? – zarpio Sep 05 '16 at 21:42
5

You can use labels over markers, here is a tutorial about GIcon.label.

You can also use GMarker.openInfoWindow.

Tip: This is the best tutorial I found about google maps api (of course after Official documentation)

Sameh Deabes
  • 2,960
  • 25
  • 30
  • Is there a way to do this using Google Maps Javascript API V3? – User May 23 '10 at 10:37
  • Also from the tutorial I'm not clear how do I set arbitrary text for the label (e.g. to give the label) – User May 24 '10 at 02:28
  • I did not try V3, but by default, google supports backward compatibility. The idea behind icon labels is to create 2 images: one for the icon itself (if you don't need to use the default icon) and another image that overlays the first one. This second image could be prepared to contain some text, which is then used as the marker label. To create this label on-the-fly you have to create this image at run-time, and of course this will be at server side, this is not hard if you are using ASP.NET for instance. – Sameh Deabes May 24 '10 at 03:35
  • As for v3, I found this sample (MarkerClusterer) but I did not try it: http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/1.0/examples/advanced_example.html – Sameh Deabes May 24 '10 at 03:35
  • If you look at MarkerClusterer (and I've used this project) they create these clusters with numbers on them and they're not being generated server side. Looking at the code however, I'm not sure exactly how they're creating the numbers on the markers. – User May 25 '10 at 01:50
  • Here is the source code of the MarkerClusterer: http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/1.0/src/markerclusterer.js Find the "ClusterMarker_" function in code, and see how it works. From the quick check of the code, they are representing the marker as a DIV with certain style/image, and the number of markers is its innerHTML. – Sameh Deabes May 25 '10 at 07:02
  • I have used a simpler library MarkerWithLabel: http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerwithlabel/docs/examples.html (source: http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerwithlabel/src/) – Jeroen K Mar 13 '12 at 15:36
5

Simplest solution:

marker = new google.maps.Marker({
  position: my_position,
  map: map,
  label: num_events+'' //Needs to be a string. No integers allowed
});

See https://developers.google.com/maps/documentation/javascript/examples/marker-labels


For more control over the layout of the marker see Valery Viktorovsky's answer

Jules Colle
  • 11,227
  • 8
  • 60
  • 67
5

Just found this tutorial: http://biostall.com/adding-number-or-letters-to-google-maps-api-markers

It doesn't look like the best solution, but it does work.

Mauro
  • 3,946
  • 2
  • 27
  • 41
2
while creating marker use the 

<script>
var marker = new google.maps.Marker({
            position: myLanLat,
            icon:'icon: 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld='+ (position) +'|FF776B|000000',
            map: map,
                  });
<script>
Selva Raj
  • 65
  • 4
1
<hr/>
1. add Google maps script To _Layout page.<br/>
     &lt;script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"&gt;   &lt;/script &gt;
<hr/>
2. Add script to your view page.

  &lt;script type="text/javascript" &gt;<br/>
   var mapLocation = [['Lucknow', 26.74561, 80.859375],<br/>
                    ['New Delhi', 28.613459, 77.695313],<br/>
                    ['Jaipur', 26.980829, 75.849609],<br/>
                    ['Ahmedabad', 22.674847, 72.333984],<br/>
                    ['Mumbai', 18.760713, 73.015135]];<br/>
    $(document).ready(function () { initialize(); });

//At view initialize load default map

function initialize() {<br/>
        var latLng = new google.maps.LatLng(22.917923, 76.992188);<br/>
        var myOptions = { center: latLng, zoom: 10,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };<br/>
        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        setMarker(map, mapLocation);
    }

function setMarker(map, mapLoc) {
    for (i = 0; i < mapLoc.length; i++) {
        var loca = mapLoc[i];
        var myLanLat = new google.maps.LatLng(loca[1], loca[2]);
        var marker = new google.maps.Marker({
            position: myLanLat,
            icon:'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld='+ ( i     + 1) +'|FF776B|000000',
            shadow:'https://chart.googleapis.com/chart?chst=d_map_pin_shadow',
            map: map,
            tittle: loca[0],
            zIndex: loca[3]
        });
    }
}

joshua
  • 2,371
  • 2
  • 29
  • 58
Sachin CR
  • 21
  • 5
1

The link above ('http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=1|FE6256|000000') can't be used via SSL. To generate and store the number images locally:

for i in {1..99}; do curl -o ./${i}_map_icon.png  "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=${i}|FE6256|000000"; echo $i; done
Szymon
  • 42,577
  • 16
  • 96
  • 114
user2611053
  • 11
  • 1
  • 2
0

Best solution would be to pass a remote or local image and text to a server side script through a url. When plotting the markers, you would use this url as the icon's value, and the server side script return a copy of your supplied image (never saved on the server mind you) with the text baked into image. Thus you could render numbers or text on custom marker images real-time as you drop them on the map.

Here is the tutorial on my blog on how to do this. - http://www.devinrolsen.com/google-maps-marker-icons-with-numbers-using-php-gd/

CalvT
  • 3,123
  • 6
  • 37
  • 54
  • 1
    Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – NathanOliver May 08 '17 at 19:00