Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaflet: How to add a text label to a custom marker icon?

Tags:

leaflet

mapbox

Is it possible to add text to a custom icon marker? I want to avoid having to edit the icon in an image editor just to add the text.

I've created my custom icon marker like so:

var airfieldIcon = L.icon({         iconUrl: 'images/airfield.png',         iconSize: [48,48] });  var airfield = L.geoJson (airfield, {     pointToLayer: function(feature,latlng){         return L.marker(latlng, {             icon: airfieldIcon         })     } }).addTo(map); 

How would I add the text "Banff Airfield" as a label to this icon? Is the easiest and most efficient way through using an image editor? if so, I will do that method, but wondering if there was a better way. Thanks!

like image 398
redshift Avatar asked Jan 13 '16 19:01

redshift


People also ask

What is Iconanchor?

icon-anchor · Unicode: f13d · Created: v3. 1 · Categories: Web Application Icons. After you get up and running, you can place Font Awesome icons just about anywhere with the <i> tag: icon-anchor. <i class="icon-anchor"></i> icon-anchor.


2 Answers

You could use a L.DivIcon:

Represents a lightweight icon for markers that uses a simple div element instead of an image.

http://leafletjs.com/reference.html#divicon

Put your image and text in it's HTML, sprinkle some CSS to make it appear the way you want and you're good to go

new L.Marker([57.666667, -2.64], {     icon: new L.DivIcon({         className: 'my-div-icon',         html: '<img class="my-div-image" src="http://png-3.vector.me/files/images/4/0/402272/aiga_air_transportation_bg_thumb"/>'+               '<span class="my-div-span">RAF Banff Airfield</span>'     }) }); 

Another option is to use the Leaflet.Label plugin:

Leaflet.label is plugin for adding labels to markers & shapes on leaflet powered maps.

  • Repository: https://github.com/Leaflet/Leaflet.label
  • Example: http://leaflet.github.io/Leaflet.label/
like image 148
iH8 Avatar answered Sep 23 '22 03:09

iH8


As of leaflet version 1.0.0, you can add a label without using a plugin (the plugin has been rolled into the core functionality).

Example:

var marker = L.marker(latlng)     .bindTooltip("Test Label",      {         permanent: true,          direction: 'right'     } ); 

This yields a marker on the map with a label of "Test Label" which is always displayed to the right of the marker's icon.

like image 24
Mark Avatar answered Sep 26 '22 03:09

Mark