Skip to content

Instantly share code, notes, and snippets.

@progapandist
Created March 3, 2021 11:19
Show Gist options
  • Select an option

  • Save progapandist/520cfa7cb3011731dba2d2607dabbb9d to your computer and use it in GitHub Desktop.

Select an option

Save progapandist/520cfa7cb3011731dba2d2607dabbb9d to your computer and use it in GitHub Desktop.

Revisions

  1. progapandist created this gist Mar 3, 2021.
    41 changes: 41 additions & 0 deletions init_mapbox.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    import mapboxgl from "mapbox-gl"; // ES6 import
    import "mapbox-gl/dist/mapbox-gl.css"; // Import module's CSS
    import MapboxDirections from "@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions";
    import "@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions.css";

    const fitMapToMarkers = (map, markers) => {
    const bounds = new mapboxgl.LngLatBounds();
    markers.forEach((marker) => bounds.extend([marker.lng, marker.lat]));
    map.fitBounds(bounds, { padding: 70, maxZoom: 15, duration: 0 });
    };

    const initMapbox = () => {
    const mapElement = document.getElementById("map");

    // ALWAYS check if selector selected
    if (mapElement) {
    console.log("Selected the map element!");
    // only build a map if there's a div#map to inject into
    mapboxgl.accessToken = mapElement.dataset.mapboxApiKey;
    const map = new mapboxgl.Map({
    container: "map",
    style: "mapbox://styles/mapbox/streets-v10",
    });

    const markers = JSON.parse(mapElement.dataset.markers);
    markers.forEach((marker) => {
    new mapboxgl.Marker().setLngLat([marker.lng, marker.lat]).addTo(map);
    });

    map.addControl(
    new MapboxDirections({
    accessToken: mapboxgl.accessToken,
    }),
    "top-left"
    );

    fitMapToMarkers(map, markers);
    }
    };

    export { initMapbox }; // ES6 module export