程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python elegantly calculates geospatial distances using two points of latitude and longitude

編輯:Python

Overview of main contents :

 

One 、 The basic principle of calculating distance according to longitude and latitude

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 :

  • First , Turn the angle of longitude and latitude coordinates into radians (rlng1,rlat1),(rlng2,rlat2)
  • then , Use the following formula to calculate :

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 :

Two 、 Get the latitude and longitude of the location

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

3、 ... and 、 Handwriting haversine Formula calculation

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

Four 、 utilize geopy Library calculation

geopy It's about geocoding Python library . It mainly has the following functions :

  • Geocoding : Convert string to geographic location .
  • Reverse geocoding : Used to convert geographic coordinates to specific addresses .
  • Calculate the distance between two points : Longitude and latitude distance and spherical distance .

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 .

5、 ... and 、 utilize haversine library Calculation

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved