I am new to Leaflet, I am currently trying to add two labels, at the first and last joint of my GeoJSON polyline. I tried to open tooltips directly on map and adding markers with coordinates and a bounded tooltip but no luck.
When refresh
function is called, polylines are added to map, but permanent tooltips bounded to the markers I add to map in the onEachFeature
function don't appear. Even tooltips added by iterating the labels
variable aren't shown.
Here is my messy code:
refresh(state, map) {
console.log("refreshing");
if(this.geoJSONLayer) {
this.geoJSONLayer.clearLayers();
}
var labels = [];
L.geoJSON(state.support_map).addTo(map);
this.geoJSONLayer = L.geoJSON(state.document_map, {
onEachFeature: function(feature, layer) {
layer.on('click', (e) => {
e.target.editing.enable();
});
L.marker(feature.geometry.coordinates[0]).bindTooltip('HEY!', {
permanent: true
}).addTo(map);
L.marker(feature.geometry.coordinates[feature.geometry.coordinates.length - 1]).bindTooltip('HEY!', {
permanent: true
}).addTo(map);
labels.push({
lat: feature.geometry.coordinates[0][0],
lng: feature.geometry.coordinates[0][1]
});
labels.push({
lat: feature.geometry.coordinates[feature.geometry.coordinates.length - 1][0],
lng: feature.geometry.coordinates[feature.geometry.coordinates.length - 1][1]
});
}
});
this.geoJSONLayer.addTo(map);
if(state.draw === 'polyline') {
this.polylineDrawer = new L.Draw.Polyline(map, {});
this.polylineDrawer.enable();
} else {
this.polylineDrawer.disable();
}
labels.forEach((label)=>{
map.openTooltip('HEY!', label, { permanent: true });
});
}
The state
variable contains what to render on map
, which is a reference to the Leaflet map. In the code there are both the two approach I tried: adding markers with tooltip and open tooltips right from map. I would simply like to show a label at the start of my polyline and one at the end of it.
What did I do wrong?
You can see the whole code here.
Best Answer
Your tooltips and markers are shown, but at the wrong location. Zooming out enough you would see them. Reason for this is that Leaflet for the input to it's methods/functions expects
[lat, lng]
order, but GeoJSON coordinates are given in[lng, lat]
order.So what is needed is just to swap the GeoJSON coordinates when using them as input to Leaflet methods, for example: