velobike route planner
by John Doe
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Turf.js/6.3.0/turf.min.js"></script>
<div id="map"></div>
CSS
body {
margin: 0;
}
#map {
position: absolute;
width: 100%;
height: 100%;
background-color: white;
}
JavaScript
/** globals */
// openrouteservice api key
const ORS_API_KEY = '5b3ce3597851110001cf6248b597693b37104dc78c0db305e9122ee6';
// isochrone radius in meters
var maxRadius = 25;
// isochrone layer
var isochroneLayer;
/** converts json data to geojson */
function json2geojson(json) {
var converted = json.map(el => {
return {
"type": "Feature",
"properties": el,
"geometry": {
"type": "Point",
"coordinates": [el.Position.Lon, el.Position.Lat]
}
}
});
return converted;
}
/** get isochrone polygon */
function getIsochrone(latlng, time) {
// create data object
var data = {"locations":[latlng],"area_units":"km","range_type":"time","range":[time*60],"options":{"avoid_features":[]}};
// send request
return new Promise((response, reject) => {
fetch('https://api.openrouteservice.org/v2/isochrones/cycling-regular',{
headers: {'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8', 'Content-Type': 'application/json; charset=utf-8', 'Authorization': ORS_API_KEY},
method: 'POST',
body: JSON.stringify(data)
})
.then(res => res.json())
.then(data => {
response(data.features[0]);
});
});
}
/** show isochrone polygon */
function addIsochrone(feature) {
if (isochroneLayer) isochroneLayer.removeFrom(map);
isochroneLayer = L.geoJSON(feature, {
pane: 'polygons',
style: {
weight: 2,
opacity: 0.8,
color: '#337ab7',
fillOpacity: 0.3,
}
}).addTo(map);
}
/** do the following on station click */
function onMarkerClick(e) {
getIsochrone([e.latlng.lng,e.latlng.lat], maxRadius)
.then(addIsochrone);
}
// initializing our map
const map = L.map('map', {preferCanvas:true}).setView([55.7,37.6], 11);
// custom panes
map.createPane('polygons');
map.getPane('polygons').style.zIndex = 200;
// adding basemap
const basemap = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
// fetching and...