Search code examples
here-api

HERE Maps for Javascript API: Calculate closest routing maneuver to the current geo position


I am using HERE Maps JS API. I am able to request a route based on start and end positions. Now, the route shows all the maneuvers in a single response like an array as shown in the figure below. How can I figure out which maneuver to select based on the latitude and longitude of current position?enter image description here


Solution

  • You should loop over maneuver array and check the distance between the maneuver's position and desired geo location using H.geo.Point#distance method, something like this:

    // ...
    // assuming we're in calculateRoute response callback
    // and result is callback's parameter
    
    var maneuver = result.response.route[0].leg[0].maneuver,
        testPosition = {lat: 50, lng: 13},
        closestManeuver,
        closestManeuverPoint,
        minDistance = Infinity;
    
    // calculate the closest maneuver
    maneuver.forEach(function(man) {
      let currManeuverPoint = new H.geo.Point(
        man.position.latitude, 
        man.position.longitude
      ),
      currDistance = currManeuverPoint.distance(testPosition);
    
      if (currDistance < minDistance) {
        minDistance = currDistance;
        closestManeuver = man;
        closestManeuverPoint = currManeuverPoint;
      }
    });
    
    console.log('closest maneuver (%s m) is at: {lat: %s, lng: %s}: \n %s', Math.round(minDistance), closestManeuverPoint.lat, closestManeuverPoint.lng, closestManeuver.instruction);
    

    I created simple jsfiddle example which shows a route in Berlin and calculates closest maneuver point (rendered as marker) on each mouse click. Check the console log for detailed information about closest maneuver point.