'Mapbox GL JS change marker image programmatically?
I am using Mapbox GL JS to display a lot of pins on a map with custom marker image:
map.on('load', function () {
map.loadImage("/path/to/pin1.png", function(error, image) {
if (error) throw error;
map.addImage("custom-marker", image);
});
map.addLayer({
id: "unclustered-point",
source: "geolocations",
filter: ["!", ["has", "point_count"]],
type: "symbol",
layout: {
"icon-image": "custom-marker",
"icon-allow-overlap": true,
"icon-anchor": "bottom",
"icon-size": 0.5
}
});
//...
});
Is there any way to change a single marker image programmatically (e.g. the clicked marker)?
Solution 1:[1]
You can add two layers, a "clicked" layer and an "unclicked" layer, then set the filter (setFilter) such that each layer filters only the clicked or unclicked features.
Solution 2:[2]
I faced the same issue and finally, I found a way and documented my findings in my medium. This will help you.https://medium.com/@sameeraviraj/how-to-add-multiple-draw-points-in-mapbox-gl-js-a40235003650
Solution 3:[3]
Swift 3 to 5
func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? {
var annotationImage = mapView.dequeueReusableAnnotationImage(withIdentifier: "marker")
var annotationImageEnd = mapView.dequeueReusableAnnotationImage(withIdentifier: "end")
if annotationImage == nil {
annotationImage = MGLAnnotationImage(image: #imageLiteral(resourceName: "trip_location"), reuseIdentifier: "marker")
return annotationImage
}else{
annotationImageEnd = MGLAnnotationImage(image: #imageLiteral(resourceName: "ic_end_marker"), reuseIdentifier: "end")
return annotationImageEnd
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | AndrewHarvey |
Solution 2 | Viraj Amarasinghe |
Solution 3 | yassine menssi |