Search code examples
javascriptlatitude-longitudehere-api

How to convert latlong data for waypoint value / calculateRoute() ? (HERE API/ Matrix API)


lat, long coordinates are saved from the geocode() function. (user typed a city and street in html input -> received lat,long data in form of (50.4342,8.4324))

how do i put variable latlong inside the waypoint0 value, without receiving errors?

var lat = 50.4342;
var long = 8.4324;
var latlong = lat + ',' + long;

function calculateRoute(platform, coordinates) 
  {


    var router = platform.getRoutingService(),
    parameters = {
      waypoint0: '', //<- insert latlong variable 
      waypoint1: '49.998700,8.249140',
      mode: 'fastest;car;traffic:enabled',
      departure: 'now'};

    router.calculateRoute(parameters,
    function (result) {
      console.log(result);
      console.log(latlongstr);
    }, function (error) {
      console.log("error");
    });
  }

how do i convert lat and long for the waypoint0 value? if i pass the lat long values inside waypoint0 manually then everything is working but i would like to do it dynamically.

i just starting out with javascript so please dont hate me if its easy to solve.

thank you very much for the help.


Solution

  • Ok i solved it myself.

    Do this:

      function geocode(platform, street2, city2) 
      {
        var street3 = street2;
        var city3 = city2; 
    
        var geocoder = platform.getGeocodingService(),
        parameters = {
          searchtext: street3 + city3 ,
          gen: '9'};
    
       geocoder.geocode(parameters,
        function (result) {
           var lat = result.Response.View[0].Result[0].Location.DisplayPosition.Latitude;
           var long = result.Response.View[0].Result[0].Location.DisplayPosition.Longitude;
           calculateRoute(platform, lat, long);
        }, function (error) {
          console.log("Retrieving Latitude and Longitude failed! Refresh the page and try again.");
        });
    
    
    
        function calculateRoute(platform,latitude,longitude) 
      {
        var x = latitude;
        var y = longitude;
        var router = platform.getRoutingService(),
        parameters = {
          waypoint0: x + "," + y,
          waypoint1: '49.998700,8.249140',
          mode: 'fastest;car;traffic:enabled',
          departure: 'now'};
    
        router.calculateRoute(parameters,
        function (result) {
          console.log(result.response.route[0].summary.distance);
        }, function (error) {
          console.log("error");
        });
      }
    

    So just call the calculateRoute() function inside the geocoder.geocode() function (pass the lat and long with it) and only then you can use the latitude and longitude within the calculateRoute() function to calculate the distance.