Reputation: 17253
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?
Upvotes: 2
Views: 1091
Reputation: 23144
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:
Transform the points into an EPSG with meter
units.
EPSG:3857
(but the result will be 0.08104046068988752mi
).32148
.Create a Distance
object with the distance calculation in meters
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
Upvotes: 4