通过两点经纬度计算范围距离的所有数据
时间: 2023-11-03 12:04:10 浏览: 154
可以使用 Haversine 公式来计算两点经纬度之间的距离。以下是一个 Python 函数,可以计算两点之间的距离(单位为千米或英里):
```python
import math
def distance(lat1, lon1, lat2, lon2, unit='km'):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
c = 2 * math.asin(math.sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
if unit == 'mi':
r = 3956
return c * r
```
这个函数需要四个参数:第一个点的纬度和经度,以及第二个点的纬度和经度。它还采用一个可选的单位参数,默认情况下为千米,但也可以设置为英里。
例如,如果您想查找距离北京市中心(39.9042° N,116.4074° E)不到10公里的所有地址,则可以使用以下代码:
```python
center_lat = 39.9042
center_lon = 116.4074
max_distance = 10 # in km
# loop through all addresses and calculate distance
for address in all_addresses:
d = distance(center_lat, center_lon, address.lat, address.lon)
if d < max_distance:
print(address)
```
这个代码将打印所有距离北京市中心不到10公里的地址。
阅读全文