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=""></script>
<!-- Include targomo leaflet full build -->
<script src="https://releases.targomo.com/leaflet/latest-full.min.js"></script>
<style>
body,
html {
margin: 0;
width: 100%;
height: 100%;
}
#map {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<!-- where the map will live -->
<div id="map"></div>
<script>
// create targomo client
const client = new tgm.TargomoClient('northamerica', '__targomo_key_here__');
// Create a Leaflet map with one of basemap, set the center of the map to Portland, Oregon.
const tileLayer = new tgm.leaflet.TgmLeafletTileLayer(client, 'Light');
var map = L.map('map', {
layers: [tileLayer],
scrollWheelZoom: false
}).setView([45.494435398006495, -122.65196800231935], 13);
// set the attribution
const attributionText = '<a href="https://www.targomo.com/developers/resources/attribution/" target="_blank">© Targomo</a>';
map.attributionControl.addAttribution(attributionText);
// 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>
Copied to clipboard