DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
What's in store for DevOps in 2023? Hear from the experts in our "DZone 2023 Preview: DevOps Edition" on Fri, Jan 27!
Save your seat
  1. DZone
  2. Coding
  3. JavaScript
  4. Distance Calculations Between Points With the HERE JavaScript SDK

Distance Calculations Between Points With the HERE JavaScript SDK

When I'm interacting with developers using HERE APIs and services, one common question I get is around distance calculations. The HERE SDK and APIs make it e...

Nic Raboy user avatar by
Nic Raboy
·
Apr. 30, 19 · Tutorial
Like (2)
Save
Tweet
Share
8.21K Views

Join the DZone community and get the full member experience.

Join For Free

When I'm interacting with developers using HERE APIs and services, one common question I get is around distance calculations. The HERE SDK and APIs make it easy to calculate paths or routes, but it isn't the most obvious if you want to pull the total distance from those calculations. In fact, there are multiple different distances that can be obtained.

As a developer, you could be searching for the distance between two points regardless of roadways. Take, for example, air travel or similar for that type of distance. You could also be searching for the distance between two points along a route that can be navigated. Think your GPS when you're driving or similar for that type of distance.

We're going to take a look at calculating these two distances using the HERE JavaScript SDK.

Calculating the Absolute Distance Between Two Points

The first example we'll look at is around the absolute distance between two points, ignoring any kind of roads or similar. Let's take a look at the following example code:

const tracyMarker = new H.map.Marker({ lat: 37.7397, lng: -121.4252 });
const stocktonMarker = new H.map.Marker({ lat: 37.9577, lng: -121.2908 });
const straightLineString = new H.geo.LineString();
straightLineString.pushPoint(tracyMarker.getPosition());
straightLineString.pushPoint(stocktonMarker.getPosition());
const straightPolyline = new H.map.Polyline(straightLineString);
map.addObject(straightPolyline);

Of course if you really wanted to try the above code, you'd need to properly configure your application and add a map, but hopefully you can get the idea. We have two markers and we're drawing a straight line between those two markers.

If we wanted to calculate the distance, we would typically make use of the haversine algorithm, because remember, the earth is not flat. To make our lives easier, the HERE JavaScript SDK takes care of this alglorithm for us.

Let's take a look at the following modification to our code:

const distance = tracyMarker.getPosition().distance(stocktonMarker.getPosition());
console.log(distance);

The above lines would print out the distance in meters. The distance function is part of the H.geo.Point class which is returned from markers when calling the getPosition function.

Calculating the Distance Along a Route

With the basic distance calculation out of the way, we can take a look at finding the route distance. After all, I probably want to know how far I'm driving when I enter information into my GPS.

Let's take a look at the following code for our example:

const params = {
    mode: "fastest;car;traffic:enabled",
    waypoint0: "37.7397,-121.4252",
    waypoint1: "37.9577,-121.2908",
    representation: "display"
};
routingService.calculateRoute(params, success => {
    const routeLineString = new H.geo.LineString();
    success.response.route[0].shape.forEach(point => {
        const [lat, lng] = point.split(",");
        routeLineString.pushPoint({
            lat: lat,
            lng: lng
        });
    });
    const routePolyline = new H.map.Polyline(
        routeLineString,
        {
            style: {
                lineWidth: 5
            }
        }
    );
    map.addObject(routePolyline);
}, error => {
    console.log(error);
});

You've probably seen some form of the above code in the documentation. Like with the previous example, you'll need to do some preparation work in your code if you actually want to run it. I'm just sharing the part that is important to us.

As it stands, we cannot easily get the distance from the above code. We need to make a modification. In the params, we need to add the following:

routeAttributes: "summary"

The summary will return information like distance, or estimated travel time. With the summary information being returned, we can access it in the success callback of the calculateRoute function:

console.log(success.response.route[0].summary.distance);

Like with our other distance calculation, this distance is also in meters.

Conclusion

You just saw how to do some basic distance calculations with your location data using the HERE JavaScript SDK. There are plenty of other scenarios, but these are the two most common that I receive when I'm at developer events.

Software development kit JavaScript

Published at DZone with permission of Nic Raboy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Mr. Over, the Engineer [Comic]
  • Implementing Infinite Scroll in jOOQ
  • Cloud-Based Transportation Management System
  • Memory Debugging: A Deep Level of Insight

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: