How to draw a line following the road in OpenLayers

javascript, openlayers, openstreetmap

Solution

Usually OpenLayers just displays raster tiles but you can't extract road geometry information out of them. You need either raw or otherwise pre-processed data for this. Both OpenLayers and Leaflet are able to display GPX files. So once you got a GPX file everything else will become easy.

Unfortunately you didn't tell us whether you want to follow it a specific road (based on a name/address? or based on coordinates?) or whether you want to display a route along several roads or something completely different.

For retrieving raw geoinformation out of OpenStreetMap there is an official API, and there is the Overpass API which is usually a lot faster and allows to specify rather complex queries. But displaying such raw data requires a lot of preprocessing first.

If you want to display a route instead then you can choose one of the available online routers for OSM, for example OSRM. Many of them offer a GPX export of the calculated route which you can then use with OpenLayers.

There are a few more options but presenting them here without knowing what you are actually trying to do would be a waste of time.

Problem

On an OSM base layer, I have drawn a line following 3 points, with an array for the points and the object/method OpenLayers.Geometry.LineString Now, I'd like this line to follow the road. Some hours spent on internet, and impossible to find a solution. Is there an object for this ? Do I have to catch some information from the tiles first ? May I ask some help please ? Here under is how I'm drawing the straight line ``` function init() { var epsg4326 = new OpenLayers.Projection("EPSG:4326"); var map = new OpenLayers.Map('map'); var osmLayer = new OpenLayers.Layer.OSM("OSM"); map.addLayer(osmLayer); var center = new OpenLayers.LonLat(-71.6, -33.7).transform(epsg4326,map.getProjectionObject()); map.setCenter(center,4); var points = new Array( new OpenLayers.Geometry.Point(-71.26,-32.47), new OpenLayers.Geometry.Point(-71.30,-32.97), new OpenLayers.Geometry.Point(-70.81,-32.89) ); var myLine = new OpenLayers.Geometry.LineString(points).transform(epsg4326, map.getProjectionObject()); var myLineStyle = {strokeColor:"#0500bd", strokeWidth:3}; var myFeature = new OpenLayers.Feature.Vector(myLine, {}, myLineStyle); var myVector = new OpenLayers.Layer.Vector("line test"); myVector.addFeatures([myFeature]); map.addLayers([myVector]); } ```

Original source