本文记录调用现有接口获取文本地点的经纬度信息,并计算各个地点之间的距离。
获取经纬度信息
- 使用现有库
import pandas as pd
from geopy.distance import geodesic
from geopy.geocoders import Nominatim
#根据地址获取经纬度
#1、使用geopy查询
from fake_useragent import UserAgent
#获取随机的User-Agent函数
def get_random_ua():
#创建User-Agent对象
ua = UserAgent()
return ua.random
def geocodeN(address):
gps=Nominatim(user_agent=get_random_ua())
location=gps.geocode(address)
return location.longitude,location.latitude
#geocodeN('湖北省武汉市中南财经政法大学南湖校区')
- 调用高德地图或百度地图API访问获取
import requests
#使用高德API
def geocodeG(address):
par = {'address': address, 'key': 'cb649a25c1f81c1451adbeca73623251'}
base = 'http://restapi.amap.com/v3/geocode/geo'
response = requests.get(base, par)
answer = response.json()
GPS=answer['geocodes'][0]['location'].split(",")
return GPS[0],GPS[1]
#使用百度API
def geocodeB(address):
base = url = "http://api.map.baidu.com/geocoder?address=" + address + "&output=json&key=f247cdb592eb43ebac6ccd27f796e2d2"
response = requests.get(base)
answer = response.json()
return answer['result']['location']['lng'],answer['result']['location']['lat']
- 批量转换
#将一份写满地址的TXT文档转换为经纬度TXT
def TXTRead_Writeline(src,dest):
ms = open(src,encoding='utf-8')
for line in ms.readlines():
with open(dest,"a",encoding='utf-8') as mon:
loc=geocodeB(line)
mon.write(loc)
mon.write("\n")
time.sleep(1)
计算距离
#自定义计算距离函数
from math import radians, cos, sin, asin, sqrt
#计算两点间距离(m)
def geodistance(lng1,lat1,lng2,lat2):
lng1, lat1, lng2, lat2 = map(radians, [lng1, lat1, lng2, lat2]) ## 经纬度转换成弧度
dlon=lng2-lng1
dlat=lat2-lat1
a=sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
distance=2*asin(sqrt(a))*6371*1000 ## 地球平均半径,6371km
distance=round(distance/1000,3)
return distance
批量计算距离
#读取数据并计算距离
data = pd.read_stata(r'C:\Users\王彤\Desktop\毕业论文\初期结果\distance_.dta')
data['distance'] = data.apply(lambda x: geodesic((x.lat0, x.lng0),(x.lat1,x.lng1)).km, axis = 1)