In Leaflet, how to know when map.fitBounds actually changed anything? - leaflet

I have a click event on a map feature that zooms into that feature when clicked by the user
Map starts like this:
When a user clicks on the map feature:
L.geoJson(geoJsonFeatureCollection, {
style,
onEachFeature
}).addTo(map)
function zoomToFeature (e) {
map.fitBounds(e.target.getBounds())
}
function onEachFeature (feature, layer) {
layer.on({
click: zoomToFeature
})
}
On a second click on the same map feature, after being already zoomed in, I'd like to forward the URL to another page (the info HTML page of that feature). But I can't distinguish both situations.
How can I know in map.fitBounds if the map bounds were already fitted, i.e., if the method actually did/zoomed/panned anything?

You can use the same calculation function from leaflet and check if it equals to the current map state:
function zoomToFeature (e) {
const bounds = e.target.getBounds();
const target = map._getBoundsCenterZoom(bounds);
if(target.zoom === map.getZoom() && map.getCenter().equals(target.center)){
// bounds already fitting
} else {
map.fitBounds(bounds);
}
}
Maybe you need to change the margin of equals. Default: .equals(target.center, 1.0E-9)

Related

how to hide the leaflet tooltip (visibility already depending on zoom level) when activating a layer?

I am interested in showing the tooltip only for a specific zoom range (>=12) at any time. With the help of this other article I could manage to almost get there but I still have the problem that the tooltip come to appear when I activate the layer in my OverlayMaps-menu, disregarding the current zoom level.
In my leaflet map I have implemented a OverlayMaps-menu, in which almost all layers are deactivated from the start. For one of these deactivated layers, my aim is to show the tooltips for all features only from a zoom level of 12 or bigger. The code is as follows:
Declaration of the variable from a geoJSON object:
var vibro_offshore = L.geoJson (vbc_offshore, {
pointToLayer: function (feature, latlng) {
return new L.Circle (latlng, {
color:'#a13c02',
})
},
onEachFeature: enCadaVBC
});
In the onEachFeature function, beside some other code regarding popup, I also have defined the tooltips:
function enCadaVBC (feature, layer) {
//declaramos un tooltip
var tooltip = L.tooltip({
content: feature.properties.Location,
permanent: true,
direction:'right',
className:'tooltip'
});
//introducimos un tooltip
layer.bindTooltip(tooltip);
Finally, I have managed to govern the visibility of the tooltips depending on the zoom level with the code suggested in the article referred above:
var lastZoom;
map.on('zoomend', function() {
var zoom = map.getZoom();
console.log(zoom);
if (zoom < 12 && (!lastZoom || lastZoom >= 12)) {
map.eachLayer(function(l) {
if (l.getTooltip) {
var toolTip = l.getTooltip();
if (toolTip) {
this.map.closeTooltip(toolTip);
}
}
});
} else if (zoom >= 12 && (!lastZoom || lastZoom < 12)) {
map.eachLayer(function(l) {
if (l.getTooltip) {
var toolTip = l.getTooltip();
if (toolTip) {
console.log(toolTip);
this.map.addLayer(toolTip);
}
}
});
}
lastZoom = zoom;
})
All this works pretty good, but when I activate the layer via mouseclick on the OverlayMaps-menu, lets say when the zoom level is 9, all the tooltips suddenly appear. I want to avoid this.
I have tried to add a closeTooltip() command right after the bindTooltip-command, but this hasnt have any effect. A consol.log for Is Tooltipopen leads to an undefined...(?)
I also tried to relocate the layer.bindTooltip command into the if-loop, but here I do get some other error related to Mercator projection and latlng, which I do not really understand...

How to get polyline coordinates React-Leaft-Draw plugin?

I use this plugin to draw lines on Leaflet map in my project:
https://github.com/alex3165/react-leaflet-draw
I want to get coordinates (lat,long) of drawn polyline, when _onCreate or later. How could i do this?
I agree, the documentation is a bit lacking, so I hope this helps anyone else trying to do this. You first implement an onCreated function that is registered on the <EditControl> component. You can then access the current layer object and its layerType from the event object that gets passed to this callback.
Depending on the shape type, you can access the coordinates of the shape via a the methods provided by Leaflet (e.g. circle). See code below.
export default DrawTool({prop1, prop2) {
const onCreated = (e) => {
if (e.layerType === 'circle') {
console.log("circle center, radius =", e.layer.getLatLng(), e.layer.getRadius())
} else {
// polygon & rectangle
console.log("polygon coordinates =", e.layer.getLatLngs()) // array of LatLng objects
} // marker or lines, etc.
// map.addLayer(e.layer) // might need?
}
const onDelete = (e) => {
// do something with e.layer
}
return (
<EditControl
position='topright'
onCreated={onCreated}
onDeleted={onDeleted}
...
/>
)
}

Toggle geojson layer interactivity

First of all, since it's my first question, I'm sorry if I make any mistakes.
I'd like to "deactivate" a Geojson Layer, composed by a feature collection with many polygons (or lines). I have seen how to create it with the option interactive = yes or interactive = no, but I can't find out how to toggle this dynamically.
Thanks in advance.
EDIT: last thing I tried was this:
var onEachFeature = function(feature, layer) {
function onmouseover(e) {
var layer = e.target;
var activeLayer = ___get_active_layergroup();
if (activeLayer === null){
layer.setStyle({
cursor: 'move'
});
} else if (activeLayer.hasLayer(layer)){
layer.setStyle({
cursor: 'pointer'
});
} else {
layer.setStyle({
cursor: 'move'
});
}
}
function onmouseout(e) {
}
return {
mouseover: onmouseover,
mouseout: onmouseout
}
}
And I put that function in the layer initialization.
___get_active_layergroup is accesible in the context.
EDIT2:
It works if instead of setStyle I use this:
var element = layer.getElement();
if (element.classList.contains("leaflet-interactive")) {
element.classList.remove("leaflet-interactive")
}
But I don't really like how it works. I can see the pointer while I'm moving the mouse blinking (because it takes a few milliseconds process the mouseover I think).

Update Leaflet GeoJson layer and maintain selected feature popup

I have a leaflet map which I am refreshing with new data from the server. You can click on the map feature and a popup will show for the point. Every time the refresh happens, I remove the layer using map.removeLayer, add the new data using L.geoJson, but the popup goes away. I want the popup to stay active with the new data. I know this probably won't work the way I'm doing it by removing the layer. Is there another way to do this that will refresh the layer data and maintain the selected feature popup?
This is the refresh function that I call after I get the new data from the server.
function refreshMapLocations() {
map.removeLayer(locationLayer);
locationLayer = L.geoJson(locations, {
onEachFeature: onEachFeature
}).addTo(map);
}
This creates the popup for each feature
function onEachFeature(feature, layer) {
if (feature.properties && feature.properties.UserName) {
layer.bindPopup(feature.properties.UserName);
}
}
This worked, I keep track of an id that I set in the popup content. After the layer is added I store the Popup that has the clickedId and do popupOpen on that.
var popupToOpen;
var clickedId;
function onEachFeature(feature, layer) {
if (feature.properties && feature.properties.UserName) {
if (feature.properties.MarkerId == clickedId) {
layer.bindPopup("div id='markerid'>"+feature.properties.MarkerId+"</div>feature.properties.UserName);
} else {
layer.bindPopup("div id='markerid'>"+feature.properties.MarkerId+"</div>feature.properties.UserName);
}
}
}
function refreshMapLocations() {
map.removeLayer(locationLayer);
locationLayer = L.geoJson(locations, {
onEachFeature: onEachFeature
}).addTo(map);
if (popupToOpen != null) {
popupToOpen.openPopup();
}
}
function initMap() {
...
map.on('popupopen', function (e) {
...
//clickedId = id from event popup
}
}

Leaflet: Removing markers from map

I load some lat / lon info, then use it to build a polyline.
I then want to add a marker at each of the polyline vertices that will show when the polyline is clicked.
The vertices should disappear if a different (or the same) polyline is clicked.
The code below creates the polyline and the vertex markers.
But the vertex markers do not ever disappear.
I've tried to do this several ways with the same result. I've tried storing the vertex markers in an array and adding them directly to the map, then map.removeLayer'ing them. That doesn't work either. Nor does it work if I use an L.featureGroup instead of a layerGroup.
Clearly I've missed the point somewhere as to how markers can be removed. Could someone point me at the error in my methodology?
// trackMarkersVisible is a global L.layerGroup
// success is a callback from an ajax that fetches trackData, an array f lat/lon pairs
success: function (trackData) {
// build an array of latLng's
points = buildTrackPointSet(trackData, marker.deviceID);
var newTrack = L.polyline(
points, {
color: colors[colorIndex],
weight: 6,
clickable: true
}
);
$(newTrack).on("click", function () {
trackMarkersVisible.clearLayers();
$.each(points, function(idx, val) {
var tm = new L.Marker(val);
trackMarkersVisible.addLayer(tm);
});
map.addLayer(trackMarkersVisible);
});
}
Without a JSFiddle or Plunker it's hard to say because i'm not sure what behaviour your getting but using the clearLayers() method of L.LayerGroup should remove all layers from that group. I would check in the onclick handler if the group already has layers: group.getLayers().length === 0 If the group is empty, add the markers, if the group has layers use clearLayers. Example in code:
polyline.on('click', function (e) {
if (group.getLayers().length === 0) {
e.target._latlngs.forEach(function (latlng) {
group.addLayer(L.marker(latlng));
});
} else {
group.clearLayers();
}
});
This works for me, see the example on Plunker: http://plnkr.co/edit/7IPHrO?p=preview
FYI: an instance of L.Polyline is always clickable by default so you can leave out the clickable: true