項目的目的是爲了查詢某個點附近某些POI的最近距離,例如查詢天安門到附近最近的商場的距離(時間)php
1.百度地圖APIweb
程序中用到百度地圖的兩個API,分別是json
(1)路線規劃服務(又名Direction API):http://lbsyun.baidu.com/index.php?title=webapi/direction-api-v2api
(2)地點檢索服務(又名Place API):http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-placeapi數組
要用這兩個API首先要申請一個key(應用類別必須是服務端),以下圖:app
路線規劃服務ide
哎呀不想寫了,直接上代碼吧(代碼有點bug,沒能實現最後的功能,可是調API服務這些是沒錯的)函數
# -*- coding:utf-8 -*- #獲取最短路徑及時間 import requests import xlrd from urllib2 import urlopen, quote import json import sys import time import math reload(sys) sys.setdefaultencoding("utf-8") class derection: #這個函數是求兩個座標點的直線距離 #參考http://blog.csdn.net/qq_29933359/article/details/53516440 def getDistance(self,origin,destination): start_lat=origin.split(',')[0] start_lng=origin.split(',')[1] end_lat = destination.split(',')[0] end_lng = destination.split(',')[1] lat1 = (math.pi / 180) * float(start_lat) lat2 = (math.pi / 180) * float(end_lat) lon1 = (math.pi / 180) * float(start_lng) lon2 = (math.pi / 180) * float(end_lng) # print start_lat,start_lng,end_lat,end_lng #地球半徑 R = 6371 distance = math.acos(math.sin(lat1) * math.sin(lat2) + math.cos(lat1) * math.cos(lat2) * math.cos(abs(lon2 - lon1))) * R*1000 # print distance return distance #直線距離少於2千米就選擇步行 def getwalkduration(self,origin,destination): # url='http://api.map.baidu.com/direction/v2/riding?' url='http://api.map.baidu.com/direction/v1?mode=walking®ion=武漢' output = 'json' ak = '···' uri = url + '&origin=' + origin + '&destination=' + destination + '&output=' + output + '&ak=' + ak req = urlopen(uri) res = req.read().decode() temp = json.loads(res) distance = temp['result']['routes'][0]['distance'] # 那個0是由於它返回的routes是一個list,因此索引0就是第一條路線 duration = temp['result']['routes'][0]['duration'] # print '距離%.2f公里,騎車耗時%d分鐘' % (float(distance) / 1000, round(int(duration) / 60)) return distance, duration #這個函數是利用百度地圖路線規劃服務求距離POI的最近距離和最短期 def getduration(self,origin,destination): url = 'http://api.map.baidu.com/direction/v2/transit?' output = 'json' ak = '···' uri = url + '&origin=' + origin + '&destination=' + destination + '&output=' + output + '&ak=' + ak req = urlopen(uri) res = req.read().decode() temp = json.loads(res) distance=temp['result']['routes'][0]['distance']#那個0是由於它返回的routes是一個list,因此索引0就是第一條路線 duration=temp['result']['routes'][0]['duration'] # print '距離%.2f公里,乘坐公交耗時%d分鐘'%(float(distance)/1000,round(int(duration)/60)) return distance,duration #這個函數是利用地點檢索服務獲取離中心點最近的POI(獲取的POI數量在10個之內) def getsortestfacility(self,origin): #選出直線距離最短的前十個設施 url='http://api.map.baidu.com/place/v2/search?&radius_limit=true' query = '公園$景區' tag='旅遊景點' output = 'json' ak = '···' for i in range(1000,6000,1000): #若是1000米距離內沒有相關POI,就讓半徑增長1000 radius = str(i) uri = url + '&query=' + query +'&tag='+tag+ '&location=' + origin + '&radius='+radius+'&output=' + output + '&ak=' + ak req = urlopen(uri) res = req.read().decode() temp = json.loads(res) destlist = [] Num=len(temp['results']) #求返回的POI的個數,下面循環range要用到 if Num==0: # print'%d米內無相關POI'%i continue else: for i in range(0,Num): lat = temp['results'][i]['location']['lat'] lng = temp['results'][i]['location']['lng'] destination=str(lat)+','+str(lng) destlist.append(destination) #存在POI就把POI的座標加入數組 # print destlist break return destlist def findnearesttop10(self,origin): destinationdata = xlrd.open_workbook( 'C://Users//Administrator//PycharmProjects//···//shopping_cinema.xlsx') destinationdata_sheet = destinationdata.sheet_by_index(1) destinationdata_rowsNum = destinationdata_sheet.nrows alldict={} for i in range(1,destinationdata_rowsNum): lat = destinationdata_sheet.cell(i, 2).value lng = destinationdata_sheet.cell(i, 1).value destination=str(lat)+','+str(lng) newdist=test.getDistance(origin,destination) key=str(destination) value=newdist alldict[key] = value # alldict.fromkeys(key,value) # print alldict sorted_dict=sorted(alldict.items(), key=lambda alldict: alldict[1]) return sorted_dict if __name__ == '__main__': print "開始計算數據,請稍等..." start_time = time.time() fh = open(r'C://Users//Administrator//PycharmProjects//···//xiaoqu_gongyuan.txt', "w") origindata = xlrd.open_workbook('C://Users//Administrator//PycharmProjects//···//HousePrice.xlsx') origindata_sheet = origindata.sheet_by_index(1) origindata_rowsNum = origindata_sheet.nrows test = derection() # 實例化對象 for i in range(1, origindata_rowsNum): m = 10000000 oriname=origindata_sheet.cell(i, 0).value orilat = origindata_sheet.cell(i, 1).value orilng = origindata_sheet.cell(i, 2).value origin=str(orilat)+','+str(orilng) sorted_dict=test.findnearesttop10(origin) top10={} count=0 for key,value in sorted_dict: count += 1 top10[key]=value if count >= 10: break # print '小區%s的top10是:%s'%(oriname,top10) for key,value in top10.items(): if value>1000: try: destination=key distance, duration = test.getduration(origin,destination) # 方法必須由實例調用 except: # print '直線距離是%s米'%(distance) continue else: # duration=round(distance/72*60) destination = key distance,duration=test.getwalkduration(origin,destination) # print '步行距離%d米,耗時%d秒'%(distance,duration) if distance < m: m = distance d=destination else: continue print '%s小區最短距離是%d米,最近的設施是:%s'%(oriname,m,d) # fh.write(str(name)+','+str(m)) fh.close() end_time = time.time() print "所有數據處理完畢,用時%.2f秒" % (end_time - start_time)