Overview of main contents :
When processing geographic data , It is often necessary to use the distance between two geographical locations . With a little ( Longitude value , Latitude value ) The longitude and latitude coordinates of the place , such as A Point latitude and longitude (30.553949,114.357399),B Point latitude and longitude (129.1344,25.5465), seek AB The distance between two points .
We know that any two points on the earth (lng1,lat1),(lng2, lat2) The latitude and longitude coordinates of , To find the distance between two points, you can use haversine The formula :
among , a Express The difference between two latitudes , namely a = rlat1 - rlat2; b Express The difference in longitude between two points , namely b = rlng1 - rlng2, among r Represents the radius of the earth .
Take the distance between Tsinghua University and Peking University as an example , Use Baidu map ( website : Baidu Maps ) Distance measurement , The distance between Tsinghua University and Peking University is about 1.8km, As shown below :
Geocoding with Gaud maps / Reverse geocoding API , To get the longitude and latitude of Peking University and Tsinghua University ,Python The code implementation is as follows :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
KEY = ' Access code of your Gaud map application '
def geocode(address):
"""
According to the place name , Get latitude and longitude
"""
parameters = {'address': address, 'key': KEY}
base = 'http://restapi.amap.com/v3/geocode/geo'
response = requests.get(base, parameters)
answer = response.json()
# print(answer)
# print(type(answer))
print(address + " Longitude and latitude of :", answer['geocodes'][0]['location'])
if __name__ == "__main__":
address1 = ' Peking University, '
lon_lat1 = geocode(address1)
address2 = ' Tsinghua University '
lon_lat2 = geocode(address2)
among ,KEY Apply for the authorized access code of Gaode map application for yourself . Just enter the address parameter , You can print out the longitude and latitude coordinates of the corresponding address .
The running result is :
The longitude and latitude of Peking University : 116.308264,39.995304
The longitude and latitude of Tsinghua University : 116.326759,40.003304
according to haversine The formula , Custom implementation python Version calculation formula , as follows :
from math import sin, asin, cos, radians, fabs, sqrt
EARTH_RADIUS = 6371.137 # The average radius of the earth is about 6371km
def hav(theta):
s = sin(theta / 2)
return s * s
def get_distance_hav(lat0, lng0, lat1, lng1):
# use haversine The formula calculates the distance between two points on the sphere
# Conversion of longitude and latitude to radian
lat0 = radians(lat0)
lat1 = radians(lat1)
lng0 = radians(lng0)
lng1 = radians(lng1)
dlng = fabs(lng0 - lng1)
dlat = fabs(lat0 - lat1)
h = hav(dlat) + cos(lat0) * cos(lat1) * hav(dlng)
distance = 2 * EARTH_RADIUS * asin(sqrt(h)) # km
return distance
if __name__ == "__main__":
result = get_distance_hav(39.995304, 116.308264, 40.003304, 116.326759)
print(" distance :{:.3}km".format(result))
The running result is :
distance :1.809km
geopy It's about geocoding Python library . It mainly has the following functions :
pip install install geopy library , The order is :
pip install geopy -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
Python The implementation code is as follows :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from geopy.distance import geodesic
if __name__ == "__main__":
distance = geodesic((39.995304, 116.308264), (40.003304, 116.326759)).km
print(" distance :{:.3f}km".format(distance))
The running results are as follows :
distance :1.812km
Handwriting haversine The distance calculated by the formula is :1.809km, And call directly geopy Library geodesic Method the calculated distance is :1.812km, The difference between the two calculation results is very small .
More information about geopy Use , You can learn official documents : Welcome to use Geopy file ! — GeoPy 2.2.0 file .
pypi Address :haversine · PyPI
Calculate the distance (in various units) between two points on Earth using their latitude and longitude.
Calculate the distance between two points on the earth with longitude and latitude ( Expressed in different units ),pip install Can be installed , The order is :
pip install haversine -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
Python The implementation code is as follows :
from haversine import haversine, Unit
if __name__ == "__main__":
# The latitude and longitude of two points
point1 = (39.995304, 116.308264)
point2 = (40.003304, 116.326759)
result1 = haversine(point1, point2, unit=Unit.KILOMETERS) # km
result2 = haversine(point1, point2, unit=Unit.METERS) # m
# Print calculation results
print(" distance :{:.3f}km".format(result1))
print(" distance :{:.3f}m".format(result2))
The running result is :
distance :1.809km
distance :1809.223m
You can find , utilize haversine The library calculates the distance between the result and the handwriting haversine The results calculated by the formula are consistent .