DEV Community

Joe Steinbring
Joe Steinbring

Posted on

How to calculate the distance between two points, using the MapQuest API

Previously, we looked at how to calculate the distance between two points using just math. The problem with that is that the distance is calculated "as the crow flies". Calculating the distance between Milwaukee and Chicago is close enough but the distance between Milwaukee and Ludington could be a problem (since Lake Michigan is a thing).

If we modify the example from last week to look at the distance between Ludington and Milwaukee, you can see what I mean.

The result comes back as 96.6 miles but if you take the ferry from Milwaukee to Muskegon, it is really 148 miles and if you go around the bottom of the lake, the distance is 333 miles. The difference is significant.

Luckily, there are services out there that you can use to do these calculations. For today's demo, we are going to look at MapQuest and specifically the the Route end-point of the Directions API.

As you can see, the API takes an API key, the origin of the trip, and the destination of the trip. It returns all of the details of the trip but for this example, we only really care about the distance. For more complex queries, MapQuest also offers a Route Matrix API. That one can go beyond a point-to-point trip and handle many more destinations.

Have any questions, comments, etc? Feel free to drop a comment, below.

Top comments (0)