Skip to content

Instantly share code, notes, and snippets.

@VictorVelarde
Last active October 11, 2018 09:45
Show Gist options
  • Save VictorVelarde/1ad0a8826c4df361d84c3a71d48942af to your computer and use it in GitHub Desktop.
Save VictorVelarde/1ad0a8826c4df361d84c3a71d48942af to your computer and use it in GitHub Desktop.
Mapbox Isochrone API + CARTO VL
<!DOCTYPE html>
<html>
<head>
<title>carto-vl</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<!-- Include CARTO VL JS -->
<script src="https://libs.cartocdn.com/carto-vl/v0.9.1/carto-vl.min.js"></script>
<!-- Include Mapbox GL JS -->
<script src="https://libs.cartocdn.com/mapbox-gl/v0.48.0-carto1/mapbox-gl.js"></script>
<!-- Include Mapbox GL CSS -->
<link href="https://libs.cartocdn.com/mapbox-gl/v0.48.0-carto1/mapbox-gl.css" rel="stylesheet" />
<style>
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
height: 100%;
width: 100%;
z-index: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
// Basemap
const map = new mapboxgl.Map({
container: 'map',
style: carto.basemaps.darkmatter,
center: [-3.6967239965247245, 40.43119726695207],
zoom: 10
});
const nav = new mapboxgl.NavigationControl();
map.addControl(nav, 'top-left');
map.on('mousemove', () => {
map.getCanvas().style.cursor = 'pointer';
});
// Mapbox API
async function isochronesCalculation(e) {
const TOKEN = 'pk.eyJ1IjoidnZlbGFyZGUiLCJhIjoiY2lzMW10aW5rMDA3aDJ5bzdvN25jaXFwYiJ9.gWQR2LQ1vXnuPx2bH_zq2g';
const { lng, lat } = e.lngLat;
const url = `https://api.mapbox.com/isochrone/v1/mapbox/driving/${lng},${lat}?contours_minutes=5,10,15&contours_colors=6706ce,04e813,4286f4&polygons=true&access_token=${TOKEN}`;
let response = await fetch(url);
let data = await response.json();
const source = new carto.source.GeoJSON(data);
const viz = new carto.Viz(`
color: opacity(ramp(buckets($contour, [5, 10, 15]), [red, orange, yellow]), 0.9)
width: 0
`);
const ISO = 'isochrones';
const isochronesLayer = new carto.Layer(ISO, source, viz);
if (map.getLayer(ISO)) {
map.removeLayer(ISO);
}
isochronesLayer.addTo(map);
}
map.on('click', isochronesCalculation)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment