I\'m working on a map that has multiple markers on it.
These markers use a custom icon, but I\'d also like to add numbers on top. I\'ve seen how this has been accomp
EASIEST SOLUTION - USE SVG
Works in: in IE9, IE10, FF, Chrome, Safari
(if you are using other browsers please "Run code snippet" and place a comment)
No external dependencies besides Google Maps API!
This is quite easy provided that you have your icon in .svg format. If that is the case just add appropriate text element and change its content to fit your needs with JS.
Add something like this to your .svg
code (this is text "section" which will be later changed with JS):
1
Example: (partially copied from @EstevãoLucas)
Important:
Use correct
tag properties. Note text-anchor="middle" x="50%" y="28"
which center longer numbers (more info: How to place and center text in an SVG rectangle)
Use encodeURIComponent()
(this probably ensures 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 = '';
// 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;
}
More info about inline SVG in Google Maps: https://robert.katzki.de/posts/inline-svg-as-google-maps-marker