Mapbox gl playground

A mapbox gl js playground for quick tryouts

by askhflajsf

HTML

<script src="	https://npmcdn.com/@turf/turf/turf.min.js"></script>
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.css">
<div id="map" data-mapbox-api-key="pk.eyJ1IjoiZmFyYWRheTIiLCJhIjoiTUVHbDl5OCJ9.buFaqIdaIM3iXr1BOYKpsQ"></div>

CSS

#map {
  height: 500px;
}

JavaScript

const mapElement = document.getElementById('map');

mapboxgl.accessToken = mapElement.dataset.mapboxApiKey;

const map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/dark-v10',
  center: [8.57112664053318, 60.2560784364510],
  zoom: 7
});


map.on('load', function() {
  const cars = JSON.parse(mapElement.dataset.cars);

  map.addSource('cars', {
    type: 'geojson',
    data: cars,
    cluster: true,
    clusterMaxZoom: 14,
    clusterRadius: 50
  });

  map.addLayer({
    id: 'clusters',
    type: 'circle',
    source: 'cars',
    filter: ['has', 'point_count'],
    paint: {
      'circle-color': [
        'step',
        ['get', 'point_count'],
        '#51bbd6',
        100,
        '#f1f075',
        750,
        '#f28cb1'
      ],
      'circle-radius': [
        'step',
        ['get', 'point_count'],
        20,
        100,
        30,
        750,
        40
      ]
    }
  });

  map.addLayer({
    id: 'cluster-count',
    type: 'symbol',
    source: 'cars',
    filter: ['has', 'point_count'],
    layout: {
      'text-field': '{point_count_abbreviated}',
      // 'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
      'text-size': 12
    }
  });

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

  map.on('click', 'clusters', function(e) {
    const features = map.queryRenderedFeatures(e.point, {
      layers: ['clusters']
    });
    const clusterId = features[0].properties.cluster_id;

    map.getSource('cars').getClusterExpansionZoom(clusterId, function(err, zoom) {
      if (err) return;

      map.easeTo({
        center: features[0].geometry.coordinates,
        zoom: zoom
      });
    });
  });


  map.addControl(
    new mapboxgl.GeolocateControl({
      positionOptions: {
   ...