Mapbox GL JS - Add new marker and remove previous marker - mapbox-gl-js

My function is supposed to display a marker over an existing icon (US Cities) when clicked/selected. The marker is an image file. Then when the user clicks on another icon, the previous marker should disappear.
It seems to work fine at first. The first marker is created when the icon is clicked. When the second icon is clicked, the marker is created and the original marker disappears. When a third icon is clicked, the marker does not appear. The console says "marker is not defined".
Here is my code:
map.on('click', 'usa_cities', function(highlightMarker) {
var markerCoordinates = highlightMarker.features[0].geometry.coordinates.slice();
var markerElement = document.createElement('div');
markerElement.id = 'marker';
// create the marker
new mapboxgl.Marker(markerElement)
.setLngLat(markerCoordinates)
.addTo(map);
map.on('click', 'usa_cities', function() {
marker.remove()
});
}),
Thank you

You don't need to create a new marker each time the user clicks. You can simply call marker.setLngLat(markerCoordinates).

Related

Show popup or tooltip on the map by default, without any interaction( mouse hover, click) in leaflet

I know there is a way to show properties by mouse hove and click event on the map, but my question is how can I show the properties without mouse hover or click event.
I tried using label pane but it's not working in my case.
// show map
mymap = L.map('map_canvas');
// For Label
mymap.createPane('labels');
// This pane is above markers but below popups
mymap.getPane('labels').style.zIndex = 650;
// Layers in this pane are non-interactive and do not obscure mouse/touch events
mymap.getPane('labels').style.pointerEvents = 'none';
var positronLabels = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png', {
attribution: '©OpenStreetMap, ©CartoDB',
pane: 'labels'
}).addTo(mymap);
layer.bindPopup(feature.properties.block_name + '</br>' + feature.properties.DIST_NAME,{
noHide: true,
direction: 'auto'
});
But still, it's not showing by default but it showing when I click on the map.
Please give me some suggestions on how to do it, I already wasted more than 10 days on this single work.
Happy coding.

How can I pull a URL stored inside a Mapbox dataset and add it to a 'click' function on a popup?

I have a function code that pulls data from the "description" field and displays it inside a popup on mouseenter, but can someone help me figure out how to pull in the URL stored inside "linkurl" and use it to open that URL when the icon is clicked? The popup displays properly over an icon, but I can't figure out how to bring the URL in as a link on click. Here's the code I'm working with:
map.on('load', function() {
// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false
});
// POINTS OF INTEREST
function showPopup(e) {
// Updates the cursor to a hand (interactivity)
map.getCanvas().style.cursor = 'pointer';
// Show the popup at the coordinates with some data
popup
.setLngLat(e.features[0].geometry.coordinates)
.setHTML(checkEmpty(e.features[0].properties.description))
.addTo(map);
}
function hidePopup() {
map.getCanvas().style.cursor = '';
popup.remove();
}
function checkEmpty(info) {
return (info) ? info : "No data";
}
// CHANGE: Add layer names that need to be interactive
map.on('mouseenter', 'points-of-interest-2019', showPopup);
map.on('mouseleave', 'points-of-interest-2019', hidePopup);
});
To add a link within the Popup itself, you can use Popup#setHTML in conjunction with the <a> tag define a hyperlink. For example:
// Show the popup at the coordinates with some data
var properties = e.features[0].properties;
popup
.setLngLat(e.features[0].geometry.coordinates)
.setHTML(
'<a href=\'' + properties.linkurl + '\'>'
+ checkEmpty(properties.description)
+ '</a>')
.addTo(map);
Since creating a Popup with the GL JS API automatically creates a DOM element as outlined in the source code here, there is currently not a way to make the entire Popup clickable to navigate to a particular link. You could instead use Popup#setHTML along with some minimal CSS to create a link which wraps the entire content added to the Popup, so that clicking the content of the Popup will open the link.
Alternatively, if you are using Marker instances and would like clicking on the marker itself to open a link, you could utilize the options.element parameter to specify a DOM element wrapped in a link to use as a marker. For example, consider a slight modification to this example:
var el = document.createElement('a');
el.href = 'https://www.mapbox.com/'
el.className = 'marker';
el.style.backgroundImage =
'url(https://placekitten.com/g/' +
marker.properties.iconSize.join('/') +
'/)';
el.style.width = marker.properties.iconSize[0] + 'px';
el.style.height = marker.properties.iconSize[1] + 'px';
// add marker to map
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.addTo(map);

click event not triggering in leaflet

I am using leaflet.js for my application.
The click event is not triggering alongwith the mouseover event.
layer.on({
mouseover: function (e) {
L.popup().setLatLng(e.latlng)
.setContent("Test")
.openOn(map);
},
click: function () {
alert("Click");
map.fire("click", e);
}
});
I am using the custom marker instead of circle marker
option.pointToLayer = function (feature, latlng) {
var marker = L.marker(latlng);
var icon = L.icon({
iconUrl: 'Image/InvestmentIcons/environmentalflow.png',
iconSize: [12, 12], // size of the icon
});
marker.options.icon = icon;
return marker;
}
What happens is that when a user tries to click on your Marker (which would trigger your "click" event listener, i.e. display your alert), they have to move first their mouse over the Marker, which opens a Popup at this position (accordingly with your "mouseover" event listener), so the Popup is now receiving the click, instead of your Marker.
You can see that your "click" listener is still working properly by positioning your mouse cursor just besides the Popup "tip", where it does not cover the Marker icon, but the mouse cursor is still somehow a little bit on the Marker:
To try it live: https://plnkr.co/edit/8Zu0cYeYATp2qY6ltn7N?p=preview
To avoid this UX issue, you could try using a Tooltip instead of a Popup for example. By default it will appear on the side of the coordinates, instead of above it (which makes the Popup cover the Marker).

Change marker icon on click leaflet

Original-markerIcon = leaflet/images/marker-icon-2x.png
current-markerIcon = leaflet/images/map-marker.png
I have many markers and I want to change marker icon of the current clicked marker.If I click again on another marker change all marker Icon to original marker and current marker with current Icon.
I also have label attached with each marker.
When I click on current Icon I want to change also the label of that marker or remove the label.
How can I achieve this ?
thank you.
Image with marker visible with original-markerIcon
EDIT-1
L.Icon.Change = L.Icon.Default.extend({
options: {
iconUrl: 'leaflet/images/map-marker.png',
iconSize: new L.Point(150, 75),
}
});
var changeIcon = new L.Icon.Change();
L.Icon.Original = L.Icon.Default.extend({
options: {
iconUrl: 'leaflet/images/marker-icon-2x.png',
iconSize: new L.Point(45, 81),
}
});
var originalIcon = new L.Icon.Original();
marker.on('click',function(e){
for(var i = 0 ; i < $scope.markers.length ; i++){
$scope.markers[i].setIcon(originalIcon);
}
})
// marker click event to show the center pano
$scope.markers[index].on('click',function(e){
$scope.markers[index].setIcon(changeIcon);
});
If i am not mistaking there is a function named as "eachLayer" in map. I think when you create a marker, leaflet gives an automatic ID for that. So you have to give that ID in "eachLayer" function. And when it finds appropriate marker, there should be a function "popupclose". To add it will be better if you show your code...!

change the current clicked marker Icon using leaflet

I am using leaflet plugin to show the marker. When I click on the current marker the icon should change the current marker only.
Again when I click on another marker change that marker to new icon and keep all other marker icon original.
Like I have 2 marker Icon
1- original Icon which I am setting when showing the marker on map
2- new marker - I want this marker icon should be set when click on marker.Only current Marker Icon should be changed and keep all other Icon Original Icon.
you can try this.
When you click the marker1, its icon will change to the one you set.
let marker1 = L.marker([e.latitude, e.longitude], { icon: greenIcon }).on('click', ()=>{
marker1.setIcon(redIcon)
}).addTo(map)
Do you have a marker layer? If yes you could first create a new icon
var customIcon = L.Icon.extend({
options: {
iconSize: [40.4, 44],
iconAnchor: [20, 43],
popupAnchor: [0, -51]
}
});
var myCustomIcon = new CustomIcon({ iconUrl: '../images/marker.png' });
After that you should get clicked marker's index inside the Layer and update the icon like this:
markersLayer[markersIndex].setIcon(myCustomIcon);