Leaflet : removing rectangle - leaflet

I need to draw a rectangle on a map with Leaflet, and remove it when I create another one.
I call a function to do that and zoom on the rectangle.
It creates the rectangle, but I'm unable to remove it when calling the function again.
I can remove it if I do that just after having created the rectangle.
What's wrong with it ?
I'm a Leaflet and Javascript beginner...
Thanks,
function showLoc(lat,lng,zoom) {
map.setView([lat,lng],zoom);
locSquare.remove(map)
//if (map.hasLayer(locSquare)) {locSquare.remove(map)};
var locSquare = L.rectangle([[lat + 0.0208333333, lng - 0.0416666666],[lat - 0.0208333333, lng + 0.0416666666]], {color: "red", weight: 2,fillColor:"red"}).addTo(map);
//if (map.hasLayer(locSquare)) {locSquare.remove(map)};
}

I have made this code from yours to produce the desired output, see below.
You will need to replace the default class name I have put in classRectangle to the one you want.
In the code you wrote there was a problem with the variable locSquare at the line 3. This variable is not defined before you try to remove it from the map because you define it two lines below with the var locSquare.
You should have put the initialization of the variable outside the function for it to work.
This is what we call the scope of a variable. If you initialize it as you do inside the function, once the function is finished you will not be able to use this variable.
Instead of using a variable, you can choose to use an option available for the Rectangle object in Leaflet : className. With this option you can specify to Leaflet that this Rectangle has to use the CSS class you provided. In this way if you want to remove the Rectangle from the map you can just specify which class you want to target.
/**
* #param {number} lat
* #param {number} lng
* #param {number} zoom
*/
function showLoc(lat,lng,zoom) {
// Here is the class we will use to name the Rectangle we want to display on the map and eventually delete
const classRectangle = 'your_class_here';
// We retrieve every Rectangle on the map with the class specified before. We should only have zero or one class
classes = document.getElementsByClassName(classRectangle);
if(classes.length > 0) // If there is more than zero element that means we already have a rectangle on the map
{
classes[0].remove(); // we remove the existing Rectangle from the DOM and the map
}
let locSquare = L.rectangle(
[
[lat + 0.0208333333, lng - 0.0416666666],
[lat - 0.0208333333, lng + 0.0416666666]
],
{
color: "red",
weight: 2,
fillColor: "red",
className: classRectangle // the option className is used to add a class to the DOM element that will be created
}
).addTo(map);
map.setView([lat, lng], zoom); // We set the view depending on the params call with the function
}

Related

Leaflet - custom tile layer - get lat long coordinates

My requirement is be able to call an api which returns me GeoJson - this api requires the bounding box in lat/long coordinates. I would like to be able to have this api called for each tile but am stuck trying to convert the L.Coords x,y,z values to bounds.
I would have thought this would be a common use case - is there another way I should be approaching this problem?
Code demonstrates my approach.
L.TileLayer.Custom = L.TileLayer.extend({
getTileUrl: (coords: L.Coords) => {
const bounds = coords?.getBounds();
const geometry = {
ymin: bounds?.getSouth(),
xmin: bounds?.getWest(),
ymax: bounds?.getNorth(),
xmax: bounds?.getEast()
};
// call api Api.call(geometry).then(...)
},
});
L.tileLayer.custom = function () {
return new L.TileLayer.Custom();
};
L.tileLayer.custom().addTo(map);

Get Marker Feature Instance in MapBox

I'm new to mapbox GL JS and am following this example:
Add custom markers in Mapbox GL JS
https://www.mapbox.com/help/custom-markers-gl-js/
Let's say I modify the example above to include 100 different animal markers. How do I change the draggable property of a specific marker after it has been added to the map?
Example: Change the draggable property of the dog marker.
It would be nice to do something like this:
map.getMarker('dog').setDraggable(true);
I don't see a way to query any of the markers added to my map or modify a specific marker's properties like setLatLng, setDraggable after they have been added to a map. There is no method to get the collection of markers added to a map. Thanks for any help!
For change marker property like draggable check its api. IE https://www.mapbox.com/mapbox-gl-js/api/#marker#setdraggable
Mapbox custom marker is build by html element. If you want to change visual display of custom marker element, you should update Its inside html. For example, here are 2 functions I use to create a div with image background then return it as a image marker
/**
* #function CustomMarkerWithIcon(): constructor for CustomMarker with image icon specify
* #param lnglat: (LngLat) position of the marker
* map: (Map) map used on
* icon: (image) object for custom image
*/
function CustomMarkerWithIcon(lnglat, map, icon) {
var el = document.createElement('div');
el.className = 'marker';
el.style.backgroundImage = 'url("' + icon.url + '")';
el.style.backgroundSize = 'cover';
el.style.width = icon.size.width;
el.style.height = icon.size.height;
el.style.zIndex = icon.zIndex;
return new mapboxgl.Marker(el)
.setLngLat(lnglat)
.addTo(map);
}
/**
* #function ChangeMarkerIcon(): change marker icon
* #param marker: (marker) marker
* icon: (image) object for custom image
*/
function ChangeMarkerIcon(marker, icon) {
var el = marker.getElement();
el.style.backgroundImage = 'url("' + icon.url + '")';
}
You're right: Mapbox GL JS doesn't store references to markers. However, you can store your own references to the markers in an array at the time that you generate them.
In this example below, I am looping over a set of GeoJSON point features and creating a custom HTML marker for each:
let markersArray = [];
geojson.features.forEach(feature => {
// create a HTML element for each feature
let el = document.createElement("div");
el.className = "marker";
el.innerHTML = `
<img src="custom-marker.png" height="20px" width="20px" />
<span class="marker-label">${feature.properties.name}</span>
`;
// make a marker for each feature and add to the map
let marker = new mapboxgl.Marker({
element: el,
anchor: "top"
})
.setLngLat(feature.geometry.coordinates)
.addTo(map);
// add to my own array in an object with a custom 'id' string from my geojson
markersArray.push({
id: feature.properties.id,
marker
});
});
This id string can be whatever you want. You can even store other parameters if you want to be able to query other things, like latitude/longitude:
markersArray.push({
id: feature.properties.id,
coordinates: feature.geometry.coordinates,
marker
});
Then, if I want to access the marker's instance members (like setDraggable), I can use Array.find() to return the first instance that matches my search parameters in markersArray:
let someIdQuery = "some-id";
let queriedMarkerObj = markersArray.find(
marker => marker.id === someIdQuery
);
queriedMarkerObj.marker.setDraggable(true);
(Note that Array.find() just returns the first instance in the array that matches your condition. Use something like Array.filter() if you want to be able to query for more than one marker.)

How to change the color of results from leaflet-knn on the map

I have displayed the the result markers for the leaflet-knn on the map with following code:
const myloc = new L.LatLng(13.7433242, 100.5421583);
var gjLayer = L.geoJson(testCities, {
onEachFeature: function(feature, layer) {
content = "<b>Name:</b> " + feature.properties.name;
layer.bindPopup(content);
}
});
var longitude = myloc.lng,
latitude = myloc.lat;
var res = leafletKnn(gjLayer).nearest(
[longitude, latitude], 5, distance);
for (i = 0; i < res.length; i++) {
map.addLayer(res[i].layer);
}
Now I want to change the color of this marker that is added or I want to change the icon.
Can anybody tell me how can I do?
Leaflet-knn is agnostic when it comes to the representation of the results - it relies on the existing L.Layers: it takes a L.GeoJSON as an input and then iterates through all its members in order to fetch all their coordinates (in the case of polylines and polygons) and then store a reference to the L.Layer for each of its coordinates.
The results of a leaflet-knn search include the original L.Layer from the L.GeoJSON that was passed at instantiation time.
Either symbolize your GeoJSON afterwards, as explained in the Leaflet tutorials, or create new markers/symbols for the results after each query.
Right now your code is relying on the default symbolization of GeoJSON data (instantiate a L.Marker with a L.Icon.Default for points). I suggest the approach of displaying your L.GeoJSON in the map to ensure that it looks like you want it to (even if it's a partial set of the data), then implementing the leaflet-knn search.

How to set the zIndex layer order for geoJson layers?

I would like to have certain layers to be always on top of others, no matter in which order they are added to the map.
I am aware of bringToFront(), but it does not meet my requirements. I would like to set the zIndex dynamically based on properties.
Leaflet has the method setZIndex(), but this apparently does not work for geoJson layers:
https://jsfiddle.net/jw2srhwn/
Any ideas?
Cannot be done for vector geometries.
zIndex is a property of HTMLElements, and vector geometries (lines and polygons) are rendered as SVG elements, or programatically as <canvas> draw calls. Those two methods have no concept of zIndex, so the only thing that works is pushing elements to the top (or bottom) of the SVG group or <canvas> draw sequence.
Also, remind that L.GeoJSON is just a specific type of L.LayerGroup, in your case containing instances of L.Polygon. Furthermore, if you read Leaflet's documentation about the setZIndex() method on L.LayerGroup:
Calls setZIndex on every layer contained in this group, passing the z-index.
So, do L.Polygons have a setZIndex() method? No. So calling that in their containing group does nothing. It will have an effect on any L.GridLayers contained in that group, though.
Coming back to your problem:
I would like to have certain layers to be always on top of others, no matter in which order they are added to the map.
Looks like the thing you're looking for is map panes. Do read the map panes tutorial.
This is one of the reason for the implementation of user defined "panes" in Leaflet 1.0 (compared to versions 0.x).
Create panes: var myPane = map.createPane("myPaneName")
If necessary, set the class / z-index of the pane element: myPane.style.zIndex = 450 (refer to z-index values of built-in panes)
When creating your layers, specify their target pane option: L.rectangle(corners, { pane: "myPaneName" })
When building through the L.geoJSON factory, you can loop through your features with the onEachFeature option to clone your layers with specified target pane.
Demo: https://jsfiddle.net/3v7hd2vx/90/
For peoples who are searching about Z-Index
All path layers (so all except for markers) have no z-index because svg layers have a fix order. The first element is painted first. So the last element is painted on top.
#IvanSanchez described good why zIndex not working.
You can control the order with layer.bringToBack() or layer.bringToFront().
With that code you have more options to control the order of the layers.
L.Path.include({
getZIndex: function() {
var node = this._path;
var index = 0;
while ( (node = node.previousElementSibling) ) {
index++;
}
return index;
},
setZIndex: function(idx) {
var obj1 = this._path;
var parent = obj1.parentNode;
if(parent.childNodes.length < idx){
idx = parent.childNodes.length-1;
}
var obj2 = parent.childNodes[idx];
if(obj2 === undefined || obj2 === null){
return;
}
var next2 = obj2.nextSibling;
if (next2 === obj1) {
parent.insertBefore(obj1, obj2);
} else {
parent.insertBefore(obj2, obj1);
if (next2) {
parent.insertBefore(obj1, next2);
} else {
parent.appendChild(obj1);
}
}
},
oneUp: function(){
this.setZIndex(this.getZIndex()+1)
},
oneDown: function(){
this.setZIndex(this.getZIndex()-1)
}
});
Then you can call
polygon.oneUp()
polygon.oneDown()
polygon.setZIndex(2)
polygon.getZIndex()
And now layergroup.setZIndex(2) are working

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