How to create numbered map markers in Google Maps V3?

I am working on a map with several markers.

These markers use a custom icon, but I would also like to add numbers on top. I saw how this was done using older versions of the API. How to do it in V3?

* Note. The title attribute creates a tooltip when you hover over a marker, but I need something that will overlap on top of the custom image, even if you don't hang on top of it.

Here's the documentation for the marker class, and none of these attributes help: http://code.google.com/apis/maps/documentation/v3/reference.html#MarkerOptions

+56
javascript google-maps google-maps-api-3
Mar 12 '10 at 23:10
source share
16 answers

Unfortunately, this is not very simple. You can create your own marker based on the OverlayView class ( example ) and put your own HTML code in it, including a counter. This will give you a very simple marker that you cannot easily drag or drop shadows, but it is very customizable.

Alternatively, you can add a label to the default marker . This will be less customizable, but should work. It also saves all the useful things a standard marker does.

Learn more about overlays in a Google article. For more information, see "Entertainment with MVC objects."

Edit: if you don't want to create a JavaScript class, you can use the Google chart API . For example:

Numbered marker:

http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=7|FF0000|000000 

Text Marker:

 http://chart.apis.google.com/chart?chst=d_map_spin&chld=1|0|FF0000|12|_|foo 

This is a quick and easy route, but it is less customizable and requires the client to upload a new image for each marker.

+62
May 7 '10 at 12:29
source share

This is how I do it in V3:

I start by loading goi google maps and inside the initialize() callback method, I load MarkerWithLabel.js , which I found here :

 function initialize() { $.getScript("/js/site/marker/MarkerWithLabel.js#{applicationBean.version}", function(){ var mapOptions = { zoom: 8, center: new google.maps.LatLng(currentLat, currentLng), mapTypeId: google.maps.MapTypeId.ROADMAP, streetViewControl: false, mapTypeControl: false }; var map = new google.maps.Map(document.getElementById('mapholder'), mapOptions); var bounds = new google.maps.LatLngBounds(); for (var i = 0; i &lt; mapData.length; i++) { createMarker(i+1, map, mapData[i]); <!-- MARKERS! --> extendBounds(bounds, mapData[i]); } map.fitBounds(bounds); var maximumZoomLevel = 16; var minimumZoomLevel = 11; var ourZoom = defaultZoomLevel; // default zoom level var blistener = google.maps.event.addListener((map), 'bounds_changed', function(event) { if (this.getZoom(map.getBounds) &gt; 16) { this.setZoom(maximumZoomLevel); } google.maps.event.removeListener(blistener); }); }); } function loadScript() { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&amp;libraries=places&amp;sensor=false&amp;callback=initialize"; document.body.appendChild(script); } window.onload = loadScript; </script> 

Then I create markers with createMarker() :

 function createMarker(number, currentMap, currentMapData) { var marker = new MarkerWithLabel({ position: new google.maps.LatLng(currentMapData[0], currentMapData[1]), map: currentMap, icon: '/img/sticker/empty.png', shadow: '/img/sticker/bubble_shadow.png', transparent: '/img/sticker/bubble_transparent.png', draggable: false, raiseOnDrag: false, labelContent: ""+number, labelAnchor: new google.maps.Point(3, 30), labelClass: "mapIconLabel", // the CSS class for the label labelInBackground: false }); } 

Since I added the mapIconLabel class to the marker, I can add some CSS rules in my css:

 .mapIconLabel { font-size: 15px; font-weight: bold; color: #FFFFFF; font-family: 'DINNextRoundedLTProMediumRegular'; } 

And here is the result:

MarkerWithIconAndLabel

+47
Oct 21 '13 at 11:51 on
source share

I don't have enough reputation to comment on the answers, but I would like to note that the Google Chart API is out of date.

On the API homepage:

The infographic part of Google Chart tools is officially outdated as of April 20, 2012

+27
Jul 05 2018-12-12T00:
source share

You can download a set of numbered icons from the sources provided on this site:

Then you can do the following:

 <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>Google Maps Demo</title> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> <script type="text/javascript"> function initialize() { var myOptions = { zoom: 11, center: new google.maps.LatLng(-33.9, 151.2), mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("map"), myOptions); var locations = [ ['Bondi Beach', -33.890542, 151.274856, 4], ['Coogee Beach', -33.923036, 151.259052, 5], ['Cronulla Beach', -34.028249, 151.157507, 3], ['Manly Beach', -33.80010128657071, 151.28747820854187, 2], ['Maroubra Beach', -33.950198, 151.259302, 1] ]; for (var i = 0; i < locations.length; i++) { var image = new google.maps.MarkerImage('marker' + i + '.png', new google.maps.Size(20, 34), new google.maps.Point(0, 0), new google.maps.Point(10, 34)); var location = locations[i]; var myLatLng = new google.maps.LatLng(location[1], location[2]); var marker = new google.maps.Marker({ position: myLatLng, map: map, icon: image, title: location[0], zIndex: location[3] }); } } </script> </head> <body style="margin:0px; padding:0px;" onload="initialize();"> <div id="map" style="width:400px; height:500px;"></div> </body> </html> 

Screenshot from the above example:

Google Numbered Marker Icons

Note that you can easily add shadow behind markers. For more information about this, check out the Google Maps API Reference: Complex Tokens .

+21
Mar 12 '10 at 23:37
source share

This has now been added to the Mapping documentation and does not require third-party code.

You can combine these two patterns:

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

https://developers.google.com/maps/documentation/javascript/examples/icon-simple

To get code like this:

 var labelIndex = 0; var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789'; function initialize() { var bangalore = { lat: 12.97, lng: 77.59 }; var map = new google.maps.Map(document.getElementById('map-canvas'), { zoom: 12, center: bangalore }); // This event listener calls addMarker() when the map is clicked. google.maps.event.addListener(map, 'click', function(event) { addMarker(event.latLng, map); }); // Add a marker at the center of the map. addMarker(bangalore, map); } // Adds a marker to the map. function addMarker(location, map) { // Add the marker at the clicked location, and add the next-available label // from the array of alphabetical characters. var marker = new google.maps.Marker({ position: location, label: labels[labelIndex], map: map, icon: 'image.png' }); } google.maps.event.addDomListener(window, 'load', initialize); 

Please note that if you have more than 35 tokens, this method will not work, since the label shows only the first character (using AZ and 0-9 means 35). Vote for this issue with Google Maps to request removal of this restriction.

+14
Aug 04 '15 at 10:05
source share

I did this using a solution similar to @ZuzEL.

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

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

enter image description here

You can see that the code creates 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 SVG using D3.js and then convert the SVG to Canvas, so I can resize the image the way I want, and after that I get Base64 from the canvas toDataURL method.

All this demo was based on my @ thiago-mata strong> command. Kudos to him.

+10
01 Oct '15 at 15:17
source share

How about this? (2015 year)

1) Get a custom marker image.

 var imageObj = new Image(); imageObj.src = "/markers/blank_pin.png"; 

2) Create a canvas in RAM and draw this image on it

 imageObj.onload = function(){ var canvas = document.createElement('canvas'); var context = canvas.getContext("2d"); context.drawImage(imageObj, 0, 0); } 

3) Write something above it

 context.font = "40px Arial"; context.fillText("54", 17, 55); 

4) Get raw data from the canvas and provide it with Google APIs instead of URLs

 var image = { url: canvas.toDataURL(), }; new google.maps.Marker({ position: position, map: map, icon: image }); 

enter image description here

Full code:

 function addComplexMarker(map, position, label, callback){ var canvas = document.createElement('canvas'); var context = canvas.getContext("2d"); var imageObj = new Image(); imageObj.src = "/markers/blank_pin.png"; imageObj.onload = function(){ context.drawImage(imageObj, 0, 0); //Adjustable parameters context.font = "40px Arial"; context.fillText(label, 17, 55); //End var image = { url: canvas.toDataURL(), size: new google.maps.Size(80, 104), origin: new google.maps.Point(0,0), anchor: new google.maps.Point(40, 104) }; // the clickable region of the icon. var shape = { coords: [1, 1, 1, 104, 80, 104, 80 , 1], type: 'poly' }; var marker = new google.maps.Marker({ position: position, map: map, labelAnchor: new google.maps.Point(3, 30), icon: image, shape: shape, zIndex: 9999 }); callback && callback(marker) }; }); 
+9
Jul 29 '15 at 19:50
source share

Google Maps version 3 has built-in support for marker marks. You no longer need to create your own images or implement third-party classes. Markers

+5
Nov 25 '15 at
source share

You can create icon shortcuts on the server side if you have programming skills. In addition to PHP, you will need the GD library on the server. It worked well for me for several years now, but admittedly difficult to sync icon images.

I do this through AJAX by sending a few parameters to determine the blank icon, text and color, as well as bgcolor to apply. Here is my php:

 header("Content-type: image/png"); //$img_url = "./icons/gen_icon5.php?blank=7&text=BB"; function do_icon ($icon, $text, $color) { $im = imagecreatefrompng($icon); imageAlphaBlending($im, true); imageSaveAlpha($im, true); $len = strlen($text); $p1 = ($len <= 2)? 1:2 ; $p2 = ($len <= 2)? 3:2 ; $px = (imagesx($im) - 7 * $len) / 2 + $p1; $font = 'arial.ttf'; $contrast = ($color)? imagecolorallocate($im, 255, 255, 255): imagecolorallocate($im, 0, 0, 0); // white on dark? imagestring($im, $p2, $px, 3, $text, $contrast); // imagestring ( $image, $font, $x, $y, $string, $color) imagepng($im); imagedestroy($im); } $icons = array("black.png", "blue.png", "green.png", "red.png", "white.png", "yellow.png", "gray.png", "lt_blue.png", "orange.png"); // 1/9/09 $light = array( TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE); // white text? $the_icon = $icons[$_GET['blank']]; // 0 thru 8 (note: total 9) $the_text = substr($_GET['text'], 0, 3); // enforce 2-char limit do_icon ($the_icon, $the_text,$light[$_GET['blank']] ); 

It is called by the client side through something like the following: var image_file = "./our_icons/gen_icon.php?blank=" + escape (icons [color]) + "& text =" + iconStr;

+3
Feb 27 '13 at 0:46
source share

My two cents show how to use the Google Maps API to solve this problem.

+2
Oct 10 2018-10-10
source share

Based on @ dave1010, answer, but with updated https links.

Numbered marker:

 https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=7|FF0000|000000 

Text Marker:

 https://chart.googleapis.com/chart?chst=d_map_spin&chld=1|0|FF0000|12|_|Marker 
0
Oct 10 '14 at 15:08
source share

You can use the Marker With Label option in google-maps-utility-library-v3. enter image description here

Just send out https://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries

0
Jun 01 '15 at 7:01
source share

I have found a better way to do this. Use Snap.svg to create svg, and then use the toDataURL () function, which creates graphic data to include as an icon. Note that I am using the SlidingMarker class for the marker, which gives me good marker movement. With Snap.svg you can create any kind of graphics and your map will look fantastic.

 var s = Snap(100, 100); s.text(50, 50, store.name); // Use more graphics here. var marker = new SlidingMarker({ position: {lat: store.lat, lng: store.lng}, map: $scope.map, label: store.name, // you do not need this title: store.name, // nor this duration: 2000, icon: s.toDataURL() }); 
0
Oct 17 '15 at 15:39
source share

EASIEST SOLUTION - USING SVG

Works in: IE9 , IE10 , FF, Chrome, Safari

(if you use other browsers, please "Run the code snippet" and post a comment)

No external dependencies except the Google Maps API!

enter image description here

This is pretty easy if you have an icon in .svg format. If so, just add the appropriate text element and change its contents to suit your needs with JS.

Add something similar to your .svg code (this is the text "section" that will be modified later using JS):

 <text id="1" fill="#20539F" font-family="NunitoSans-ExtraBold, Nunito Sans" font-size="18" font-weight="600" letter-spacing=".104" text-anchor="middle" x="50%" y="28">1</text> 

Example: (partially copied from @ EstevãoLucas)

Important: Use the correct <text> tag properties. Note that text-anchor="middle" x="50%" y="28" , in the center of which there are more numbers (more: How to place and center the text in the SVG rectangle )

Use encodeURIComponent() (this probably guarantees compatibility with IE9 and 10)

 // Most important part (use output as Google Maps icon) function getMarkerIcon(number) { // inline your SVG image with number variable var svg = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="40" height="40" viewBox="0 0 40 40"> <defs> <rect id="path-1" width="40" height="40"/> <mask id="mask-2" width="40" height="40" x="0" y="0" fill="white"> <use xlink:href="#path-1"/> </mask> </defs> <g id="Page-1" fill="none" fill-rule="evenodd"> <g id="Phone-Portrait---320" transform="translate(-209 -51)"> <g id="Group" transform="translate(209 51)"> <use id="Rectangle" fill="#FFEB3B" stroke="#F44336" stroke-width="4" mask="url(#mask-2)" xlink:href="#path-1"/> <text id="1" fill="#20539F" font-family="NunitoSans-ExtraBold, Nunito Sans" font-size="18" font-weight="600" letter-spacing=".104" text-anchor="middle" x="50%" y="28">' + number + '</text> </g> </g> </g> </svg>'; // use SVG without base64 see: https://css-tricks.com/probably-dont-base64-svg/ return 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg); } // Standard Maps API code var markers = [ [1, -14.2350040, -51.9252800], [2, -34.028249, 151.157507], [3, 39.0119020, -98.4842460], [5, 48.8566140, 2.3522220], [9, 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) { var pos = new google.maps.LatLng(point[1], point[2]); new google.maps.Marker({ position: pos, map: map, icon: getMarkerIcon(point[0]), }); bounds.extend(pos); }); map.fitBounds(bounds); } 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> </head> <body> <div id="map_canvas"></div> </body> <script src="script.js"></script> </html> 

Additional information about the embedded SVG in Google Maps: https://robert.katzki.de/posts/inline-svg-as-google-maps-marker

0
Jan 02 '17 at 18:11
source share

There may be those who are still looking for this, but believe that the Google Dynamic icons are outdated and other map icon libraries are too ugly.

Add a simple marker with any number inside using the URL. In Google Drive, using Google My Maps, numbered icons are created when a map layer with a "Number Sequence" is used, and then markers / points on the map are added.

Looking at the source code, Google has its own way of doing this through the URL:

 https://mt.google.com/vt/icon/name=icons/onion/SHARED-mymaps-container-bg_4x.png,icons/onion/SHARED-mymaps-container_4x.png,icons/onion/1738-blank-sequence_4x.png&highlight=ff000000,0288D1,ff000000&scale=2.0&color=ffffffff&psize=15&text=56&font=fonts/Roboto-Medium.ttf 

Above url

enter image description here

I haven’t played with him too much, but by changing the hexadecimal color codes in the 'highlight' parameter (the color parameter does not change the color as you think), the value of 'text' can be set to any line, and you can make a beautiful round icon with any number / value inside. I am sure that other options may also be useful.

One caveat with this approach, which knows when Google will remove this URL from the world!

0
Jan 24 '19 at 12:06
source share

Here are custom icons with an updated "visual refresh" style that can be quickly generated using a simple .vbs script. I also included a large pre-generated set that can be used with several color options at once: https://github.com/Concept211/Google-Maps-Markers

Use the following format when connecting to image files hosted on GitHub:

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

color
red, black, blue, green, gray, orange, purple, white, yellow

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

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

-one
Aug 04 '15 at 19:48
source share



All Articles