Draw isolines with MapLibreGL
This code sample shows how to calculate an isoline and draw it with MapLibreGL
by Geoapify
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/1.9.0/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/1.9.0/mapbox-gl.css">
<div id="my-map"></div>
CSS
body {
margin: 0;
padding: 0;
}
#my-map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
JavaScript
// The API Key provided is restricted to JSFiddle website
// Get your own API Key on https://myprojects.geoapify.com
var myAPIKey = "6dc7fb95a3b246cfa0f3bcef5ce9ed9a";
var map = new mapboxgl.Map({
center: [151.21336314711994, -33.8712586],
zoom: 9,
container: 'my-map',
style: `https://maps.geoapify.com/v1/styles/klokantech-basic/style.json?apiKey=${myAPIKey}`,
});
map.addControl(new mapboxgl.NavigationControl());
map.on('load', () => {
// get 30-minute drive isochrone for St Mary's Cathedral, College Street, Sydney NSW 2000, Australia
var isochroneUrl = `https://api.geoapify.com/v1/isoline?lat=-33.8712586&lon=151.21336314711994&type=time&mode=drive&range=1800&apiKey=${myAPIKey}`;
fetch(isochroneUrl).then(response => response.json()).then(isochroneData => {
showGeoJSONData(isochroneData);
});
});
function showGeoJSONData(geojson) {
const sourceId = 'my-isochrone';
const lineLayerId = 'my-isochrone-layer-lines';
const fillLayerId = 'my-isochrone-layer-fill';
if (map.getSource(sourceId)) {
// romove the old one if exist
map.removeLayer(lineLayerId);
map.removeLayer(fillLayerId);
map.removeSource(sourceId);
}
map.addSource(sourceId, {
'type': 'geojson',
'data': geojson
});
// add contour
map.addLayer({
'id': lineLayerId,
'type': 'line',
'source': sourceId,
'layout': {
'line-join': 'round',
'line-cap': 'round'
},
'paint': {
'line-color': '#ff69b4',
'line-width': 3
}
});
// add filling
map.addLayer({
'id': fillLayerId,
'type': 'fill',
'source': sourceId,
'paint': {
'fill-color': '#ff69b4',
'fill-opacity': 0.1
}
});
}