使用天地图服务为地名数据找到地理坐标

起因是 x老师想从微信公布的中国历史文化名镇名村拟公布名单里,找出对应镇、村的地理坐标。

名单里的镇、村信息其实格式非常标准,也很完整,如下:

第一反应是希望查找天地图接口中的行政区划API,因为该接口可以返回对应行政区划的面状要素信息。

但是通过阅读接口说明,我们发现:行政区接口仅返回县级以上行政区划信息。而我们需要的是镇、村信息。

因此,只能放弃,将村镇信息作为“地名地址”数据,使用地理编码API,查找镇政府和村中心的点要素信息。

 

对于天地图服务的使用,和百度地图、高德地图一样,需要注册后,获得注册码,作为向服务器发送请求时的一个参数。但目前天地图服务的请求次数并没有限制,十分适宜作为科研的数据来源。

代码如下:(已把token替换为一串无意义的数字了)

 1  -*- coding: utf-8 -*-
 2 """
 3 Created on Wed Dec 26 09:43:56 2018
 4 利用天地图的行政区划api完成地址解析
 5 
 6 
 7 @author: shirley
 8 """
 9 
10 import requests
11 import pandas as pd
12 
13 application_key='57df1fe06eb196694bb0bb939ecc0'
14 
15 input_filename = "village.txt"
16 output_filename="village.csv"
17 
18 def getParam(searchWord):    
19     
20     url = 'http://api.tianditu.gov.cn/geocoder?ds={"keyWord":"'+searchWord+'"}&tk='+application_key
21     print(url)
22     try:
23         response = requests.request('GET',url)        
24         response.encoding = 'utf-8'
25         location = response.json()
26         return location['location']
27     except Exception as ex:
28         print(ex)
29         
30           
31     csvFile = open('error.csv','a',encoding='utf-8')
32     csvFile.write(url+',')
33     return ''
34  
35 txt = pd.DataFrame.from_csv(input_filename,sep='',encoding='utf-8',header=None)
36 shp_lat_list = []
37 shp_lon_list = []
38 
39 for address_name in txt.values:
40     shape = getParam(address_name[0].strip())
41     shp_lat_list.append(shape['lat'])
42     shp_lon_list.append(shape['lon'])
43     
44 txt['lat'] = shp_lat_list
45 txt['lon'] = shp_lon_list
46 txt.to_csv(output_filename)

 

posted @ 2018-12-26 15:19  ShirleyLoveGIS  阅读(4823)  评论(0编辑  收藏  举报