Search code examples
javascriptmapboxmapbox-gl-js

Mapbox unclustered circle change to icon


How can i change this to be an icon instead of this circle with color? I have tried using "layout" & "options" instead of "paint". I also looked in here but didn't find anything which could fit with this. I'm still new to Mapbox/Leaflet.

                 map.addLayer({
                 id: 'unclustered-point',
                 type: 'circle',
                 source: 'people',
                 filter: ['!', ['has', 'point_count']],
                 paint: {
                 'circle-color': '#21ba45',
                 'circle-radius': 11,
                 'circle-stroke-width': 3,
                 'circle-stroke-color': '#fff'
                 }
                 });

Solution

  • In order to use an icon in Mapbox, you need to load your image first (png, webp, or jpg format):

    map.loadImage(
      './marker-icon.png', // Path to your image here
      (error, image) => {
      if (error) throw error;
         map.addImage('icon_name', image);
    });  
    

    Then you have to change your layer type from circle to symbol.

    The fill applies to a form but not to an image, so you'll have to use layout instead. Here is an example:

    map.addLayer({
      'id': 'layer_id',
      'type': 'symbol',
      'source': {
        'type': 'geojson',
        'data': data
      },
      'layout': {
        'icon-image': 'icon_name', // The name has to match with the image loaded
        'icon-size': 0.85,
        "icon-allow-overlap": false // This can be 'true' if you want to display all the markers 
        },
    });