MapSnippets logoMapSnippets logo

Display a Route with OpenLayers

OpenLayers

Display a driving route between two points using the OSRM routing API rendered as a vector feature on an OpenLayers map.

progress_activityLoading map...
var startCoord = [2.3522, 48.8566];
var endCoord = [2.2945, 48.8584];
var markerLayer = new ol.layer.Vector({
  source: new ol.source.Vector({
    features: [
      new ol.Feature({ geometry: new ol.geom.Point(ol.proj.fromLonLat(startCoord)) }),
      new ol.Feature({ geometry: new ol.geom.Point(ol.proj.fromLonLat(endCoord)) })
    ]
  }),
  style: new ol.style.Style({ image: new ol.style.Circle({ radius: 8, fill: new ol.style.Fill({ color: '#e63946' }), stroke: new ol.style.Stroke({ color: '#fff', width: 2 }) }) })
});
var routeLayer = new ol.layer.Vector({ source: new ol.source.Vector(), style: new ol.style.Style({ stroke: new ol.style.Stroke({ color: '#457b9d', width: 5 }) }) });
var map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({ source: new ol.source.XYZ({ url: 'https://api.maptiler.com/maps/streets-v4/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_KEY', attributions: '&copy; <a href="https://www.maptiler.com/copyright/">MapTiler</a>' }) }),
    routeLayer, markerLayer
  ],
  view: new ol.View({ center: ol.proj.fromLonLat([2.32, 48.858]), zoom: 14 })
});
fetch('https://router.project-osrm.org/route/v1/driving/' + startCoord[0] + ',' + startCoord[1] + ';' + endCoord[0] + ',' + endCoord[1] + '?overview=full&geometries=geojson')
  .then(function(r) { return r.json(); })
  .then(function(data) {
    var coords = data.routes[0].geometry;
    var feature = new ol.format.GeoJSON().readFeature({ type: 'Feature', geometry: coords }, { featureProjection: 'EPSG:3857' });
    routeLayer.getSource().addFeature(feature);
  });

How it works

This example fetches a driving route from the OSRM public routing API and displays it on the map. OSRM returns the route geometry as GeoJSON, which OpenLayers can parse directly.

Two marker points mark the start and end of the route. The OSRM URL format is /route/v1/driving/{lng1},{lat1};{lng2},{lat2} with geometries=geojson to get GeoJSON output. The overview=full parameter ensures the complete route geometry is returned.

The route GeoJSON is parsed with ol.format.GeoJSON using featureProjection: 'EPSG:3857' to convert from WGS84 to the map’s projection.

Key APIs

API Description Docs
OSRM Route API Calculate driving routes between points project-osrm.org
ol.format.GeoJSON Parse GeoJSON geometry into features openlayers.org
ol.style.Stroke Style the route line openlayers.org

FAQ

Why OSRM and not MapTiler for routing?

MapTiler does not provide a routing API. OSRM is a free, open-source routing engine suitable for demos and prototypes.

Can I add waypoints to the route?

Yes. Add more coordinate pairs separated by ; in the OSRM URL, e.g., lng1,lat1;lng2,lat2;lng3,lat3.

Common mistakes

  • Using MapTiler API for routing: it has no routing endpoint. Use OSRM instead
  • Forgetting featureProjection: 'EPSG:3857' when parsing the GeoJSON route
  • Using overview=simplified which reduces route detail: use overview=full for accurate display
auto_awesome

Build maps using OpenLayers with AI

Generate code like this display a route with openlayers example using the OpenLayers skill in your IDE.