Search code examples
javascriptmapbox-glmapbox-gl-js

Show markers behind polygons


I have created circle (type polygon, with computed coordinates by this formula - still not sure if this is best way to render circle...)

and some markers, representing cities. I prefer markers, because they are html elements and I can style them.

Circle serves as a radius for selecting cities.

My question is, how can I position these markers behind circle? Circle is part of canvas, and markers are separated divs, so there won't help any z-index.

Or should I create those markers somehow as points in canvas?

Looking exactly for this behaviour, only in mapboxgl.


Solution

  • Here is an example: https://jsfiddle.net/kmandov/vzc0o86g/

    You can use turf-circle to create a circle using a specified radius and units. Turf-circle generates a geojson object that can be added to its own layer.

    var center = {
      "type": "Feature",
      "properties": {
        "marker-color": "#0f0"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [-77.1117, 38.8739]
      }
    };
    
    var lasso = turf.circle(center, 5, 20, 'kilometers');
    

    Then you add it to its own layer. I've called it lasso:

      map.addSource('lasso', {
        'type': 'geojson',
        'data': lasso
      });
    
      map.addLayer({
        'id': 'lasso',
        'type': 'fill',
        'source': 'lasso',
        'paint': {
          'fill-color': '#f1f075',
          'fill-opacity': 0.8
        }
      });  
    

    Then you add the layer containing the stations by specifying the layer above(example). This will make sure that the lasso layer is above the stations layer:

      map.addLayer({
        'id': 'stations',
        'type': 'circle',
        'source': 'stations',
        'paint': {
          'circle-color': '#feb24c',
          'circle-opacity': 1,
          'circle-radius': 5
        }
      }, 'lasso'); // lasso is the layer above