Leaflet Routing API GeoJSON Results
This code example shows you how to get GeoJSON results from the Routing API, and display them in Leaflet.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet-src.js" crossorigin="" type="text/javascript"></script>
<script src="https://releases.targomo.com/leaflet/latest-full.min.js"></script>
<script src="../_shared/tgm-utils.js"></script>
<style>
body, html {
margin: 0;
width: 100%;
height: 100%;
}
#map {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>// Initialize map with TgmExampleUtils (Portland, Oregon)
const { client, map } = TgmExampleUtils.initLeafletMap({
apiKey: '__targomo_key_here__',
region: 'northamerica',
center: [45.494435398006495, -122.65196800231935],
zoom: 13
});
// Define source and target locations which are passed into the Targomo route service.
let targets = [
{ id: 1, lat: 45.5142865031511, lng: -122.64175415039064 },
{ id: 2, lat: 45.47842910891348, lng: -122.61789321899415 }
];
let source = { id: 0, lat: 45.49780456353945, lng: -122.67642974853517 };
// The travel options used to determine which routes should be searched for
const options = {
travelType: 'car',
maxEdgeWeight: 3600,
edgeWeight: 'time',
pathSerializer: 'geojson',
// yes, "polygon"... this comes from a legacy implementation when polygons were the only service.
// Will be changing in the future to a more generalized approach.
polygon: {
srid: 4326
}
};
// Requesting routes from the Targomo API.
client.routes.fetch([source], targets, options).then(result => {
result.forEach(featureCollection => {
L.geoJSON(featureCollection, {
style: {
color: '#ff7800',
weight: 5,
opacity: 0.5
}
}).addTo(map);
});
});</script>
</body>
</html>
Copied to clipboard