mapboxgl.Marker how to remove - mapbox-gl-js

i'm use to
Reference https://docs.mapbox.com/mapbox-gl-js/example/drag-a-marker/
var marker = new mapboxgl.Marker({
draggable: true
})
.setLngLat([0, 0])
.addTo(map);
how to remove marker?
marker = new mapboxgl.Marker({
draggable: true,
})
.setLngLat([0, 0])
.addTo(map);
marker.remove() /// fail
i want remove marker

marker.addTo(map).setLngLat([0, 0]).remove();

I found this answer here and it worked for me (there are other answers there too, but this is the only one that worked for me). If you pass an html element with a given className (in this case "marker") when you create new markers, you can remove them all with jquery like this.
import $ from 'jquery';
GeoJson.features.forEach(function(marker) {
var el = document.createElement('div');
el.className = 'marker';
new mapboxgl.Marker(el).setLngLat(marker.geometry.coordinates).addTo(map);
});
$( ".marker" ).remove();

Related

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 can I Open Multiple Popups in Leaflet Marker at a time

Map` like this:
L.Map = L.Map.extend({
openPopup: function(popup) {
this._popup = popup;
return this.addLayer(popup).fire('popupopen', {
popup: this._popup
});
}
});
But I am using leaflet. Is there anyway to extent like so that i can prevent closing my marker popup?
L.mapbox.accessToken = constant.accessToken;
var map = L.mapbox.map('map', 'mapbox.streets', {zoomControl: true});
Update Dec 2017
Leaflet popup options have been extended to include { autoClose: false } which has the required effect :
var my_marker = L.marker([my_lat, my_lng], {icon: my_icon})
.addTo(map)
.bindPopup('My Popup HTML', {closeOnClick: false, autoClose: false});
Let me quote the Leaflet documentation on L.Popup:
Used to open popups in certain places of the map. Use Map.openPopup to open popups while making sure that only one popup is open at one time (recommended for usability), or use Map.addLayer to open as many as you want.
In order to open several popups, instantiate them using L.popup(latlng, options), then .addTo(map) them.
Define an array:
let map=L.map('mymap');
...
var markers = L.markerClusterGroup();
...
var marker=[];
marker[0]= L.marker([latitud1,longitud1]).addTo(map).bindPopup('Hola 0',{autoClose: false, closeOnClick: false});
marker[1]= L.marker([latitud2,longitud2]).addTo(map).bindPopup('Hola 1',{autoClose: false, closeOnClick: false});
To put on the map:
marker.forEach(function(marker) {
markers.addLayer(marker);
map.addLayer(markers);
});
Show the popup for only one:
var curPos = marker[0].getLatLng();
map.setView(new L.LatLng(curPos.lat,curPos.lng), 13);
marker[0].openPopup();
Show all popups:
marker.forEach(function(marker) {
var popup = marker.getPopup();
marker.bindPopup(popup.getContent()).openPopup();
});
Close all popups:
map.eachLayer(function (layer) {
layer.closePopup();
});

Reuse existing map instance for Leaflet directive

I'm trying to add the Leaflet Editable functionality to my current map which map is created by the leaflet directive. I'm getting the L.map instance with:
leafletData.getMap().then(function(map) {
// where map is the Leaflet map instance
}
However the Leaflet editable needs to set editable: true when the map is created.
So, is there a way to create a L.map instance
var map = L.map('map', {editable: true});
and then attach it to the Leaflet angular directive?
UPDATE:
I tried to add a hook to Leaflet
L.Map.addInitHook(function () {
this.whenReady(function () {
this.editTools = new L.Editable(this, this.options.editOptions);
console.log('L.map', this);
});
}
It creates the editTools successfully but the
map.editTools.startPolyline();
is still not working
Did you try adding editable: true to your defaults?
angular.extend($scope, {
defaults: {
editable: true
},
center: {
lat: 51.505,
lng: -0.09,
zoom: 8
}
});
<leaflet defaults="defaults" lf-center="center" height="480px" width="640px"></leaflet>
For anyone looking like me to make an existing map editable
var map = L.map('map', {editable: true});
is the same as
var map = L.map('map');
map.editTools = new L.Editable(map);

Update or destroy popup in openlayers3

I try to build a map with openlayers3 with a group of markers and popups. The markers and the popups work so far, but when I click on one marker (popup shown) and then -without clicking in the map again- on another one, it shows a popup with the same content as the first one. I have already done research, but can't find something helpful. So here's the part for my popups:
//popup
var element = document.getElementById('popup');
var popup = new ol.Overlay({
element: element,
positioning: 'bottom-center',
stopEvent: false
});
map.addOverlay(popup);
// display popup on click
map.on('click', function(evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature, layer) {
return feature;
});
if (feature) {
var geometry = feature.getGeometry();
var coord = geometry.getCoordinates();
popup.setPosition(coord);
$(element).popover({
'placement': 'top',
'html': true,
'content': feature.get('information')
});
$(element).popover('show');
} else {
$(element).popover('destroy');
}
});
Hope somebody can help me. Thanks!
I was having the same issue and found my solution here https://gis.stackexchange.com/questions/137561/openlayers-3-markers-and-popovers
Try changing your
$(element).popover({
'placement': 'top',
'html': true,
'content': feature.get('information')
});
to
$(element).attr('data-placement', 'top');
$(element).attr('data-html', true);
$(element).attr('data-content', feature.get('information'));
I've made an example for you. Take a look!
You gotta "write" some content on each marker.
http://embed.plnkr.co/hhEAWk/preview

Leaflet & Mapbox: OpenPopup not working

I've an issue with the leaflet openPopup method.
showMap = function(elements) {
var jsonp = 'http://a.tiles.mapbox.com/v3/blahblahblah.jsonp';
var m = new L.Map("my_map").setView(new L.LatLng(51.5, -0.09), 15);
var geojsonLayer = new L.GeoJSON();
var PlaceIcon = L.Icon.extend({
iconSize: new L.Point(25, 41),
shadowSize: new L.Point(40, 35),
popupAnchor: new L.Point(0, -30)
});
var icon = new PlaceIcon(__HOME__ + '/images/leaflet/marker.png');
var marker;
for (var i = 0; i < elements.length; i++) {
var address = $("<div/>").html(elements[i].address).text();
var latlng = new L.LatLng(elements[i].latitude, elements[i].longitude);
marker = new L.Marker(latlng, {icon: icon}).bindPopup(address);
if (i == 0) {
marker.openPopup();
}
m.addLayer(geojsonLayer).addLayer(marker);
}
// Get metadata about the map from MapBox
wax.tilejson(jsonp, function(tilejson) {
m.addLayer(new wax.leaf.connector(tilejson));
});
}
When I click on a marker I have the popup open. But I would like to have the first popup open when the map is loaded. (and open other popups on markers click)
AnNy ideas ?
Put openPopup call after you add the marker to the map and you should be fine.
I'm assuming that when you click on a marker you see the popup but you're not getting the popup of the first marker to show automatically when the map is loaded?
First, it doesn't look like you're actually using GeoJSON so a GeoJSON layer isn't necessary (you can just use a FeatureLayer) but that shouldn't cause any issues. Whatever layer group you use you should only be adding it to the map once and then adding all child layers to the LayerGroup. You're currently adding the geojsonLayer multiple times in your "for" loop which you don't want to do.
Second, you have to call marker.openPopup() after the marker is added to the map.
Try changing your code around to looks something like this:
var layerGroup = new L.FeatureGroup();
layerGroup.addTo( m );
for (var i = 0; i < elements.length; i++) {
var address = $("<div/>").html(elements[i].address).text();
var latlng = new L.LatLng(elements[i].latitude, elements[i].longitude);
marker = new L.Marker(latlng, {icon: icon}).bindPopup(address);
//You don't add the marker directly to the map. The layerGroup has already
//been added to the map so it will take care of adding the marker to the map
layerGroup.addLayer( marker );
if (i == 0) {
marker.openPopup();
}
}
I had this issue and fixed it with adding a timeout right after I added the marker on the map.
marker.addTo(this.map).bindPopup('Info');
setTimeout(() => {
marker.openPopup();
}, 500);
I don't know why but on some page, I need to apply timeout. In any case it's my workaround, hope this works for some of you too.
First add your map then put openPopup():
L.marker([lat, long]).bindPopup('Your message').addTo(map).openPopup();