python +高德地图API调用
生活随笔
收集整理的這篇文章主要介紹了
python +高德地图API调用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1.地理/逆地理編碼
第一步:申請key
第二步:發(fā)起http/https請求
第三步:接收請求返回的數(shù)據(jù)(JSON或XML格式)
返回的參數(shù)通過請求參數(shù) output 指定,默認(rèn)為 JSON 形式。返回的省市區(qū)信息為簡要地址信息
def address(address):url="http://restapi.amap.com/v3/geocode/geo?key=%s&address=%s"%('你的key',address)data=requests.get(url)contest=data.json()#返回經(jīng)度和緯度contest=contest['geocodes'][0]['location']return contest批量地址編碼
def geocode_batch(address_list):location_list = []num_reqs = len(address_list) // 20for index in range(num_reqs):sl = slice(index * 20, (index + 1) * 20)#每20個進(jìn)行解析address_picked = address_list[sl] address = '|'.join(address_picked) # 用“|”拼接地址url = 'http://restapi.amap.com/v3/geocode/geo'params = {'address':address, 'key':'你的key', 'batch':True # 要傳batch參數(shù),False為單點查詢}try:res = requests.get(url, params, timeout=10)for add, geo in zip(address_picked, res.json()['geocodes']):if geo['location']: # 當(dāng)?shù)刂峰e誤時,該地址的location為空location = map(float, geo['location'].split(','))else:print('address:{} can\'t be geocoded.'.format(add))location = [None] * 2 # 異常值用None代替location_list.append(location)except Exception as e:print(e)location_list += [[None, None]] * len(address_picked)return location_list不同寫法:
import requests# 執(zhí)行一次高德地圖地理逆編碼的查詢 # 輸入值:coordList -> 經(jīng)緯度的序列,currentKey -> 當(dāng)前使用的Key # 返回值:resultList -> 查詢成功,返回結(jié)果地址的序列 # -1 -> 執(zhí)行當(dāng)前查詢時Key的配額用完了 # -2 -> 執(zhí)行當(dāng)前查詢出錯 def geocode(locationlist):res=[]for add in locationlist:url = 'https://restapi.amap.com/v3/geocode/regeo?key=你的key&location='+add# print(url)response = requests.get(url=url)answer = json.loads(response.text)adress = answer['regeocode']['formatted_address'] # adress = answer['regeocode']['addressComponent']['province'] + \ # answer['regeocode']['addressComponent']['city'] + \ # answer['regeocode']['addressComponent']['district']+\ # answer['regeocode']['addressComponent']['township']res.append(adress)return res2.路徑規(guī)劃
driving 可以換成walking https://restapi.amap.com/v3/direction/driving?origin=116.45925,39.910031&destination=116.587922,40.081577&output=xml&key=<用戶的key> def get_route(origin,destination):key = '你的key'url = https://restapi.amap.com/v3/direction/driving?origin={origin}&destination={destination}&output=xml&key=<你的key>res = request.get(url)res = res.textjsonData=json.loads(res)return jsonData def get_route_info(start,end): routeplan=[]for o in start:for d in end:route=[]#起點route.append(o)#終點route.append(d)#起點終點轉(zhuǎn)換為經(jīng)緯度ori=address(o)des=address(d)#路線規(guī)劃info=get_route(ori,des)#status為0時,info返回錯誤原;否則返回“OK”。詳情參閱info狀態(tài)表if info["info"]=='OK':#起終點步行距離try:walk_distance=info['route']['distance']except:walk_distance='null'route.append(walk_distance)# 路線出租車費用try:taxi_cost=info['route']['taxi_cost']except:taxi_cost='null'route.append(taxi_cost)#路線時間try:duration=info['route']['transits'][0]['duration']except:duration='null'route.append(duration)#路線費用try:price=info['route']['transits'][0]['cost']except:price='null'route.append(price)#路線距離try:distance=info['route']['transits'][0]['distance']except:distance='null'route.append(distance)print(o,d,taxi_cost,duration,price,distance)routeplan.append(route)return routeplan3.搜索poi
#關(guān)鍵字搜索 https://restapi.amap.com/v3/place/text?keywords=北京大學(xué)&city=beijing&output=xml&offset=20&page=1&key=<用戶的key>&extensions=all #周邊搜索 https://restapi.amap.com/v3/place/around?key=<用戶的key>&location=116.473168,39.993015&radius=10000&types=011100 #多邊形搜索 https://restapi.amap.com/v3/place/polygon?polygon=116.460988,40.006919|116.48231,40.007381|116.47516,39.99713|116.472596,39.985227|116.45669,39.984989|116.460988,40.006919&keywords=kfc&output=xml&key=<用戶的key> #id查詢 https://restapi.amap.com/v3/place/detail?id=B0FFFAB6J2&output=xml&key=<用戶的key> def PolygonSearch(address_list):address = '|'.join(address_list) # 用“|”拼接地址inputUrl = "https://restapi.amap.com/v3/place/polygon?polygon=" + address + "&offset=20&page=1&types=010000&output=json&key=0ff30ea4c08544b5df4ed773a5a6636f"response = requests.get(inputUrl)# 返回結(jié)果,JSON格式resultAnswer = response.json()# 返回結(jié)果中的狀態(tài)標(biāo)簽,1為成功,0為失敗resultStatus = resultAnswer['status']if resultStatus == '1': # 返回成功# 讀取返回的POI列表resultList = resultAnswer['pois']if len(resultList) == 0: # 返回的POI列表為空print("當(dāng)前返回結(jié)果為空!")else:# 返回的POI列表不為空,則遍歷讀取所有的數(shù)據(jù)for j in range(0, len(resultList)):saveId = str(resultList[j]['id']) # POI編號saveName = str(resultList[j]['name']) # POI名稱saveType = str(resultList[j]['type']) # POI類別saveTypecode = str(resultList[j]['typecode']) # POI類別編號saveAddress = str(resultList[j]['address']) # POI地址saveLocation = str(resultList[j]['location']) # POI坐標(biāo)print([saveId, saveName, saveType, saveTypecode, saveAddress, saveLocation])else:print("當(dāng)前返回結(jié)果錯誤!")4.天氣查詢
url = "https://restapi.amap.com/v3/weather/weatherInfo" key = '你的key' data = {'key': key, "city": 320100} req = requests.post(url, data) info = req.json()總結(jié)
以上是生活随笔為你收集整理的python +高德地图API调用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Parallel()
- 下一篇: 种子软件下载种子慢怎么解决