Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change marker color and icon on clicking a marker in mapbox?

I am new to Mapbox. I have created a custom style map in mapbox studio and then add the markers using geoJson. Here is the sample code:

mapboxgl.accessToken = 'pk.eyJ1Ijoic2Fua3ljc2Uhhcc.mb22KHuonjywQ-eaWQ';
var map = new mapboxgl.Map({
container: 'map_geo',
style: 'mapbox://styles/abcd/cipjtsdhyh04ebam5tndf4jaj',
zoom: 3.7,
center: [81.30, 22.76]
});
var geoJson = {
"type": "FeatureCollection",
 "features": [{
     "type": "Feature",
    "properties": {
        "title": "Nagpur",
          "description": "Nagpur",
         "marker-symbol": "marker",
     },
    "geometry": {
         "coordinates": [79.0882, 21.1845],
         "type": "Point"
    },
    "id": "223e9579f03849c87abec10dfed64c37"
 }, {
    "type": "Feature",
    "properties": {
        "title": "Lucknow",
        "description": "Lucknow",
        "marker-symbol": "marker",
    },
    "geometry": {
        "coordinates": [80.9462, 26.8467],
        "type": "Point"
    },
    "id": "2cc757705489152c8bccb33635708427"
 }]
};

map.on('load', function () {
map.addSource("markers", {
    "type": "geojson",
    "data": geoJson

});

map.addLayer({
    "id": "markers",
    "type": "symbol",
    "source": "markers",
    "layout": {
        "icon-image": "{marker-symbol}-15",
        "text-field": "{title}",
        "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
        "text-offset": [0, 0.6],
        "text-anchor": "top",
    },
    "paint": {
            "text-size": 16,
            "text-color": "#fff",
        }
});
});
map.scrollZoom.disable();
map.on('click', function (e) {
var features = map.queryRenderedFeatures(e.point, { layers: ['markers']    });

if (!features.length) {
    return;
}

// here I want to change the marker color to highlight the selected marker

});

Now I want to change the marker color on clicking any of the marker to display the selected marker. Thanks in advance.

like image 256
sankycse Avatar asked Jun 28 '16 06:06

sankycse


1 Answers

Thanks for the question!

You will find this example helpful in implementing the functionality you've requested: https://www.mapbox.com/mapbox-gl-js/example/hover-styles/

The basic workflow is as follows:

  • create two layers of markers: one that displays markers in the unhighlighted style and one that displays markers in the highlighted style
  • hide all markers from the highlighted styled layer using a filter
  • listen for the click event
  • find the marker under the cursor using queryRenderedFeatures
  • display the marker on the highlighted layer using a filter

We are working on ways to make this process more straightforward!

like image 196
Lucas Wojciechowski Avatar answered Sep 25 '22 17:09

Lucas Wojciechowski