CHEBURASHKA
CHEBURASHKA

Reputation: 1713

How do websites get the distance between two geographic locations?

I want to embed a feature on my website that would tell the distance between two adresses, let's say adress 1 : 100 Main St, IL ... and adress 2 : 200 Lincoln St, ..

I know one way: I could use Selenium to go to Google maps and then bring the distance in miles.

Is there any more efficient way?

Upvotes: 0

Views: 302

Answers (1)

David
David

Reputation: 218960

Depends on how accurate you need it to be, I suppose. The first thing you're going to want to do is geocode those addresses into latitude/longitude coordinates. Google provides a handy API for doing just that. Once you have those coordinates, it's a matter of math to determine the distance between them.

I once wrote a blog post with such a calculation in it. The setup was a little different, I was selecting records from a database of known latitude/longitude coordinates based on a defined distance, but the math is essentially the same. From my query you can basically pull out just the calculation part and replace the "center_latitude" and "center_longitude" with one of your coordinates, and the "Latitude" and "Longitude" with another. Something like this:

ACOS(
  COS($latitudeA * (PI()/180)) *
  COS($longitudeA* (PI()/180)) *
  COS($latitudeB * (PI()/180)) *
  COS($longitudeB * (PI()/180)) +
  COS($latitudeA * (PI()/180)) *
  SIN($longitudeA * (PI()/180)) *
  COS($latitudeB * (PI()/180)) *
  SIN($longitudeB * (PI()/180)) +
  SIN($latitudeA * (PI()/180)) *
  SIN($latitudeB * (PI()/180))
) *
(
  ($equatorial_radius * $polar_radius) /
  (
    SQRT(
      ($equatorial_radius * $equatorial_radius) -
      (
        (
          ($equatorial_radius * $equatorial_radius) -
          ($polar_radius * $polar_radius)
        ) *
        (
          COS($latitudeA) *
          COS($latitudeA)
        )
      )
    )
  )
)

Where:

  • $latitudeA is the latitude of the first coordinate
  • $longitudeA is the longitude of the first coordinate
  • $latitudeB is the latitude of the second coordinate
  • $longitudeB is the longitude of the second coordinate
  • $equitorial_radius is the radius of the Earth around the equator
  • $polar_radius is the radius of the Earth along the poles
  • SIN, COS, SQRT, ACOS, etc. are math functions in whatever code you're using

This should result in a very accurate distance between the two, using whatever units of measurement you use in the radius values. (I used US miles.) Accurate to within a few meters, if not smaller.

The reason for all this math is to account for the curvature of the Earth (to include the bulging at the equator) in order to plot the distance between the two points along the surface of that curve.

Upvotes: 1

Related Questions