python 使用GeoPy批量地理编码脚本

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用GeoPy批量地理编码脚本相关的知识,希望对你有一定的参考价值。

This Python script utilizes the [GeoPy geocoding library](https://github.com/geopy/geopy) to batch geocode a number of addresses, using various services until a pair of latitude/longitude values are returned.

[https://gist.github.com/rgdonohue/c4beedd3ca47d29aef01](https://gist.github.com/rgdonohue/c4beedd3ca47d29aef01)
# import the geocoding services you'd like to try
from geopy.geocoders import ArcGIS, Bing, Nominatim, OpenCage, GeocoderDotUS, GoogleV3, OpenMapQuest
import csv, sys

print 'creating geocoding objects!'

arcgis = ArcGIS(timeout=100)
bing = Bing('your-API-key',timeout=100)
nominatim = Nominatim(timeout=100)
opencage = OpenCage('your-API-key',timeout=100)
geocoderDotUS = GeocoderDotUS(timeout=100)
googlev3 = GoogleV3(timeout=100)
openmapquest = OpenMapQuest(timeout=100)

# choose and order your preference for geocoders here
geocoders = [googlev3, bing, nominatim]

def geocode(address):
    i = 0
    try:
        while i < len(geocoders):
            # try to geocode using a service
            location = geocoders[i].geocode(address)

            # if it returns a location
            if location != None:
                
                # return those values
                return [location.latitude, location.longitude]
            else:
                # otherwise try the next one
                i += 1
    except:
        # catch whatever errors, likely timeout, and return null values
        print sys.exc_info()[0]
        return ['null','null']

    # if all services have failed to geocode, return null values
    return ['null','null']

    
print 'geocoding addresses!'

# list to hold all rows
dout = []

with open('data.csv', mode='rb') as fin:

    reader = csv.reader(fin)
    j = 0
    for row in reader:
        print 'processing #',j
        j+=1
        try:
            # configure this based upon your input CSV file
            street = row[4]
            city = row[6]
            state = row[7]
            postalcode = row[5]
            country = row[8]
            address = street + ", " + city + ", " + state + " " + postalcode + " " + country
            
            result = geocode(address)
            # add the lat/lon values to the row
            row.extend(result)
            # add the new row to master list
            dout.append(row)
        except:
            print 'you are a beautiful unicorn'

print 'writing the results to file'

# print results to file
with open('geocoded.csv', 'wb') as fout:
    writer = csv.writer(fout)
    writer.writerows(dout)

print 'all done!'

以上是关于python 使用GeoPy批量地理编码脚本的主要内容,如果未能解决你的问题,请参考以下文章

Python地理位置信息库geopy的使用:基本使用

Python地理位置信息库geopy的使用:根据中心点坐标,方向,距离计算坐标

这里批量地理编码 API 停止工作 - HTTP 错误 500

Geopy 异常处理

python gdal处理瓦片金字塔吗

如何防止 Geopy 出现此速率限制器错误?