2

How will I show the route between two points?

I have created points with below code.

var iconFeature = new ol.Feature({
          geometry: new ol.geom.Point([8637791.36, 1456487.82]),
          name: 'Police Station',
          population: 4000,
          rainfall: 500
        });
var vectorSource = new ol.source.Vector({
  features: [iconFeature]
});

var vectorLayer = new ol.layer.Vector({
  source: vectorSource,
  title: 'point_layer'
});

1 Answer 1

3

Unless you simply want to link the points with a straight line you would need to use a route API. The are several alternatives which work by making an xhr get request which returns a json containing a set of results from which a linestring can be extracted. All need an API key and (unless you want to pay) there will be some usage limits. Input and output is usually in LonLat so you must transform coordinates and geometries to and from EPSG:3857. If you have a Bing maps API key I suggest you use the Microsoft service as it has an option to get a very detailed linestring https://msdn.microsoft.com/en-us/library/gg636956.aspx

Here's a simple example to show the road route equivalent for the straight line in your earlier question. The API uses [Lat,Lon] coordinates so in the coversions to and from openlayers coordinates the arrays need to be reversed as well as transformed.

  var coordinates = [[8623931.28, 1449016.75],[8637791.36, 1456487.82]];

  var start = ol.proj.transform(coordinates[0], 'EPSG:3857', 'EPSG:4326').reverse().toString();
  var end = ol.proj.transform(coordinates[1], 'EPSG:3857', 'EPSG:4326').reverse().toString();

  var url = "https://dev.virtualearth.net/REST/v1/Routes?wp.0=" + start + "&wp.1=" + end +
            "&routeAttributes=routePath&key=" + bingKey;

  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        var linestring = JSON.parse(xhr.responseText).resourceSets[0].resources[0].routePath.line.coordinates;
        for (var i=0; i<linestring.length; i++) {
          linestring[i].reverse();
        }
        var layerLines = new ol.layer.Vector({
          source: new ol.source.Vector({
            features: [new ol.Feature({
              geometry: new ol.geom.LineString(linestring).transform('EPSG:4326', 'EPSG:3857'),
              name: 'Line'
            })]
          }),
        });
        map.addLayer(layerLines);   
      }
    }
  }

  xhr.onerror = function(e) { console.log("error"); }
  xhr.ontimeout = function(e) { console.log("timeout"); }

  xhr.open("GET", url, true);
  xhr.timeout = 3000;
  xhr.send();
1
  • it's just awesome, thanks
    – Anupam
    Aug 13, 2021 at 12:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.