Search code examples
djangogeospatialpostgisgeodjango

Calculating distance between two PointField (s) - Why is my result incorrect?


I am trying to calculate the distance between two locations in miles however the result that I am getting is incorrect.

The reason I think its incorrect is because I put locations (latitude and longitude) on this website and I get the distance in miles as 0.055. Here are the details from my code

PointField A : (-122.1772784, 47.7001663)
PointField B : (-122.1761632, 47.700408)
Distance : 0.001141091551967795

However, according to the website, the distance should be

Distance: 0.055 miles

Here is how I am calculating the distance.

This is my model

class modelEmp(models.Model):
       user                = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
       location            = models.PointField(srid=4326,max_length=40, blank=True, null=True)  
       objects             = GeoManager() 

and this is how I calculate the distance

 result = modelEmpInstance.location.distance(PointFieldBLocation)
   where result = 0.001141091551967795

Any suggestions on what I might be doing wrong here and why my result is different from the website?


Solution

  • Your calculation is not wrong but the result is in the EPSG:4326's units, which are degrees. In order to calculate the distance in the wanted unit, we need to do the following:

    1. Transform the points into an EPSG with meter units.

      • If you don't care much about the accuracy of the calculations, you can use the EPSG:3857 (but the result will be 0.08104046068988752mi).
      • If you do care about the accuracy of your calculation though, you need to find an EPSG with meter units that are appropriate for your location. Since your points are located around the Seattle area, the appropriate EPSG is 32148.
    2. Create a Distance object with the distance calculation in meters

    3. Finally, convert it to miles:

      from django.contrib.gis.measure import Distance
      
      result = Distance(
          m = modelEmpInstance.location.transform(
              32148, clone=True
          ).distance(PointFieldBLocation.transform(32148, clone=True)
      )
      print(
          'Raw calculation: {}\nRounded calculation: {}'
          .format(result.mi, round(result.mi, 2)
      )
      

      This will print:

      Raw calculation: 0.0546237743898667 
      Rounded calculation: 0.055