Leaflet GeoJSON DivIcon Label from feature attribute
https://gis.stackexchange.com/questions/245621/how-to-label-geojson-points-in-leaflet
by matt wilkie
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.1.0/leaflet.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.1.0/leaflet.js"></script>
<p>Trying to draw
<a href="https://gis.stackexchange.com/questions/245621/how-to-label-geojson-points-in-leaflet">
Leaflet GeoJSON <b>DivIcon label from feature attribute</b>
</a></p>
<div id="mapid"></div>
CSS
#mapid {width: 100%;height: 600px;border: thin dotted;}
.my-div-icon {
background-color: transparent;
border: thin solid red;
text-align: center;
padding: 1em;
font-size: 1em;
}
JavaScript
var mb_token = 'pk.eyJ1IjoibWFwaGV3IiwiYSI6ImNqNGE0bHljNzEwNHQzMnA3cmFkMnZpMXkifQ.nRZ79Ob2sd6nLu-cVHPiLA'
var home = [60.672923, -135.024628];
var mymap = L.map('mapid').setView(home, 17);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', { attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
maxZoom: 18,
id: 'mapbox.satellite',
accessToken: mb_token
}).addTo(mymap);
var centre = L.marker(home).addTo(mymap);
var data_points = {
"type": "FeatureCollection",
"name": "test-points-short-named",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "name": "1" }, "geometry": { "type": "Point", "coordinates": [ -135.02507178240552, 60.672508785052223 ] } },
{ "type": "Feature", "properties": { "name": "6"}, "geometry": { "type": "Point", "coordinates": [ -135.02480935075292, 60.672888247036376 ] } },
{ "type": "Feature", "properties": { "name": "12"}, "geometry": { "type": "Point", "coordinates": [ -135.02449372349508, 60.672615176262731 ] } },
{ "type": "Feature", "properties": { "name": "25"}, "geometry": { "type": "Point", "coordinates": [ -135.0240752514004, 60.673313811878423 ] } }
]};
var pointLayer = L.geoJSON(null, {
pointToLayer: function(feature,latlng){
label = String(feature.properties.name) // must be string, can't use straight 'feature.properties.attribute'
console.log("Label is: " + label);
var myIcon = L.divIcon({className: 'my-div-icon'});
return new L.marker(latlng,
{icon: myIcon,
html: label,
});
}
});
pointLayer.addData(data_points);
mymap.addLayer(pointLayer);