Created
March 3, 2021 11:39
-
-
Save progapandist/a0f92f3b5d3fbadf25d386e00f8aa3f2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", | |
}); | |
map.on("load", function () { | |
const directions = new MapboxDirections({ | |
accessToken: mapboxgl.accessToken, | |
unit: "metric", | |
profile: "mapbox/cycling", | |
}); | |
map.addControl(directions, "top-left"); | |
directions.setOrigin("Berlin"); | |
directions.setDestination("Brandenburg"); | |
const markers = JSON.parse(mapElement.dataset.markers); | |
markers.forEach((marker) => { | |
new mapboxgl.Marker().setLngLat([marker.lng, marker.lat]).addTo(map); | |
directions.addWaypoint(0, [marker.lng, marker.lat]); | |
}); | |
fitMapToMarkers(map, markers); | |
}); | |
} | |
}; | |
export { initMapbox }; // ES6 module export |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment