How do I remove a Leaflet polyline using marker coords? - leaflet

I've placed my markers and drawn the polylines between them and it's working great.
I've also given the user the ability to remove a marker using the following function
function hide(marker) {
map.closePopup();
map.removeLayer(marker);
}
Now, when a marker is removed I'd also like to remove the polyline. I've been doing a lot of searching but haven't come across my specific issue: I'm using pixel coordinates and need to remove the polyline between two markers.
markers
var marker1 = L.marker(map.unproject([8706, 7789], map.getMaxZoom()));
var marker2 = L.marker(map.unproject([8302, 5273], map.getMaxZoom()));
var marker3 = L.marker(map.unproject([9303, 7251], map.getMaxZoom()));
polylines
polyline = L.polyline([
map.unproject([8706, 7789], map.getMaxZoom()),
map.unproject([8302, 5273], map.getMaxZoom()),
map.unproject([9303, 7251], map.getMaxZoom())
]);
So when a user removes marker1, the polyline disappears between marker1 and marker2, but remains between marker2 and marker3, and so on down the line...
How is this accomplished?

You can add the polylines to the markers. And if the marker is removed you can read out the lines and remove them too.
marker1 = L.marker([51.498912, -0.122223],{connectedLines: []}).addTo(mymap);
marker2 = L.marker([51.496988, -0.056305],{connectedLines: []}).addTo(mymap);
poly1 = L.polyline([marker1.getLatLng(),marker2.getLatLng()]).addTo(mymap);
marker1.options.connectedLines.push(poly1);
marker2.options.connectedLines.push(poly1);
function removeMarkerLine(e){
var marker = this;
if(marker.options && marker.options.connectedLines){
var lines = marker.options.connectedLines;
lines.forEach(function(line){
mymap.removeLayer(line);
});
}
mymap.removeLayer(marker);
};
https://jsfiddle.net/falkedesign/3aukgm7t/

Simplest way, keep track of which polylines belongs to which two markers, and if one is removed you also remove that one.
Can be easily accomplished using layer groups.

Related

Having Leaflet markers visible in more than one layer

I want some of my Leaflet markers visible in more than one layer on my Openstreetmap map.
By example: London is harbor and is also a capital city.
So I want to see the London marker when I select only the layer 'harbors' or the layer 'capital cities'.
But the normal behaviour of Leaflet markers and layers seems to be that London only shows up when both layers 'harbors' and 'capital cities' are selected.
How to achieve to show up the London marker if just one of the two layers is selected?
Code:
var harbor = L.layerGroup().addTo(map);
var capital = L.layerGroup().addTo(map);
var marker1 = L.marker([51.5, 0]);
marker1.addTo(harbor);
marker1.addTo(capital);
var overlays = { "Capital": capital, "Harbor": harbor};
L.control.layers(null, overlays).addTo(map);
The link #Tordanik gave, was helpfull.
Adding this code does the job:
map.on("overlayremove", function(o) {
if (map.hasLayer(capital)) {
map.removeLayer(capital);
map.addLayer(capital);
}
if (map.hasLayer(harbor)) {
map.removeLayer(harbor);
map.addLayer(harbor);
}
});
Steps taken after an ovelayremove-click:
Test each layers if it is active
Remove this layer
Place this layer with his markers back
Result: all the markers in this layer are visible again.

How to remove a marker from leaflet map

I have a marker in my leaflet map like
marker = new L.Marker([lat,lon],{icon:flagIcon,title: "Drage me to change your location"}).addTo(map);
marker.dragging.enable();
marker.on('dragend', function(e){
var coords = e.target.getLatLng();
var lat = coords.lat;
var lon = coords.lng;
console.log("Lat : "+lat+" Lng: "+lon);
document.getElementById("lat").value=lat;
document.getElementById("long").value=lon;
document.getElementById("placeName").value="location on map";
updateAnchor();
map.panTo({lon:lon,lat:lat})
if(flag!=0){
map.removeLayer(cir);
cir = L.circle([lat,lon],circleOptions).addTo(map);
refreshMarkers(flag);
}
});
If the marker is already exist i want to remove it and and a new one.For that i added a code like
if (marker) {
map.removeLayer(marker); // remove
}
But i couldn't remove the older marker.How to solve this issue
The marker you're adding isn't the same object as the marker that's already on the map. If you want to be able to reference (eg to remove) a marker later, save a copy of the marker object in a global.
var oldmarker;
marker = <your code here>
oldmarker = marker;
Then
if (map.hasLayer(oldmarker)) {
map.removeLayer(oldmarker);
}
Try:
if (map.hasLayer(marker)) {
map.removeLayer(marker); // remove
}
If this is not helping pls add more code to your question, when do you want to remove the marker and how you add the new one

How to draw a path between two nodes using Leaflet

I have a set of lat and long points which form a route from source to destination. I have used polyline method of Leaflet to draw the path between the source to destination, but it gives a scrambled path.
var firstpolyline = new L.polyline(latlong, {
color: 'red',
weight: 3,
opacity: 0.5,
smoothFactor: 1
});
firstpolyline.addTo(mym[![enter image description here][1]][1]ap);
The latlong in the above code is an array of latitude and longitude points. But it gives a scrambled output like this:
imgur.com/aZrGa.jpg
But the latlong points form a single correct path from source to destination. I have been using polyLine. What mistake am I doing? Should I use some other methods of Leaflet?
Edit after #ivansanchez comment
The latlong arrays are of type L.LatLng(x,y) where L is the Leaflet object. Here is a snippet:
1. var mymap = L.map('mapid').setView([17.387140, 78.491684], 13);
2. L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: "© <a href='http://osm.org/copyright'>OpenStreetMap</a> contributors"
}).addTo(mymap);
3. var latlngs = [
[15.89625,80.53544],
[15.89626,80.53542],
[15.89628,80.53536],
[15.89617,80.53539],
[15.89621,80.53547]
];
4. var path = L.polyline.antPath(latlngs,{"delay":400,"dashArray":[10,20],"weight":5,"color":"black","paused":true,"reverse":false}
).addTo(mymap);
5. mymap.addLayer(path);
mymap.fitBounds(path.getBounds());
EXPLANATION:
To set the map view on given latlongs([17.387140, 78.491684]), 13 means zoom.
Adding tiles on the maps.
Latlongs.
Drawing polylines ant paths by setting css.
Add the layer to the path.
It was my mistake, Polyline works properly. I had an array of latlng that were not in an order. Putting an ordered latlng points helped me plot the route correctly between source and destination.

Leaflet polylines not working

I'm trying to show Polylines in Leaflet but it doesn't seem to work. Am I missing anything or...? p.s. Coordinate pairs do not contain the same values, so it should yield lines...
//this adds markers to the map, which works
var d = {};
d.coordinates = [[lat,lng],[lat,lng]]
var latLngs = d.coordinates.map(function (c) {
var marker = L.marker(c).addTo(map);
return {
lat: c[0],
lng: c[1]
};
});
//This 'should' add polylines but doesn't ...
var polyline = L.polyline(d.coordinates, { color: 'red', weight: 12 }).addTo(map);
I tried all sorts of variations on the code above, varying with instantiation/factory method like: new L.polyline() vs L.polyline() and trying upper- and lowercase Polyline. I tried passing arrays of [double, double] and [L.LatLng, L.LatLng] and even [{lat:lat,lng:lng}] but nothing seems to work... I really must be overlooking a simple thing...
I'm using Leaflet 0.7.
Edit:
As shown in the jsFiddle by ghybs it should work. I updated my code to the following:
var firstpolyline = L.polyline(d.coordinates, {
color: 'red',
weight: 12
}).addTo(map);
I also added identical logging statements in both the jsFiddle and my solution.
console.log(firstpolyline); //polyline for jsFiddle
console.log(map);
console.log(d.coordinates);
Those yield this (left is custom solution which is not showing a line, right is jsFiddle which is showing a line). Manually copy-pasting different coordinates pairs of my solution to the jsFiddle just works...:
I'm really lost here :(
There is no reason to add an extra .polyline after the factory L.polyline().
var polyline2 = L.polyline(d.coordinates, {color: 'red', weight: 12}).addTo(map);
Demo: http://jsfiddle.net/ve2huzxw/48/
Side note: you should use a single equal sign (=) for assignment in d.coordinates == [[lat,lng],[lat,lng]]

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