检查R中是否存在街道地址

时间:2016-04-06 04:13:00

标签: r google-maps geocoding

我正在尝试编写一个简单的代码来检查街道地址是否存在:

在我的第一次尝试中,我把写地址给了我正确的地址:

addr <- '2147 Newhall Street,Santa Clara,CA 95050'  
url = paste('http://maps.google.com/maps/api/geocode/xml?address=',  addr,'&sensor=false',sep='')  
doc = xmlTreeParse(url) 
root = xmlRoot(doc) 
lat = xmlValue(root[['result']][['geometry']][['location']][['lat']]) 
long = xmlValue(root[['result']][['geometry']][['location']][['lng']]) 
lat
"37.3386004"
long
"-121.9405759"

但如果我写错了街道地址,它仍然给我坐标:

addr <- 'xyz,Santa Clara,CA 95050'  # set your address here
url = paste('http://maps.google.com/maps/api/geocode/xml?address=',      addr,'&sensor=false',sep='')    
doc = xmlTreeParse(url) 
root = xmlRoot(doc) 
lat = xmlValue(root[['result']][['geometry']][['location']][['lat']]) 
long = xmlValue(root[['result']][['geometry']][['location']][['lng']]) 
lat
"37.3539663"
long
"-121.9529992"

我确定上面的街道地址不存在,但我仍然得到一些坐标。无论如何,如果没有有效的街道地址,我可以返回NA值或一些标志吗?

1 个答案:

答案 0 :(得分:2)

ggmap包中已经有一个很好的Google Maps地理编码API包装器。如果您将output参数设置为more,则会返回loctype,表示地址是否精确匹配(rooftop)或近似值(approximaterange_interpolatedgeometric_center)。有关详细信息,请参阅the documentation

library(ggmap)
addr <- '2147 Newhall Street,Santa Clara,CA 95050' 
geocode(addr, 'more')
# Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=2147%20Newhall%20Street,Santa%20Clara,CA%2095050&sensor=false
#         lon     lat           type loctype                                     address    north
# 1 -121.9406 37.3386 street_address rooftop 2147 newhall st, santa clara, ca 95050, usa 37.33995
#      south      east      west street_number          route    locality
# 1 37.33725 -121.9392 -121.9419          2147 Newhall Street Santa Clara
#   administrative_area_level_2 administrative_area_level_1       country postal_code
# 1          Santa Clara County                  California United States       95050

addr <- 'xyz,Santa Clara,CA 95050'
geocode(addr, 'more')
# Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=xyz,Santa%20Clara,CA%2095050&sensor=false
#        lon      lat        type     loctype                    address    north    south
# 1 -121.953 37.35397 postal_code approximate santa clara, ca 95050, usa 37.37448 37.32314
#        east      west postal_code    locality administrative_area_level_2
# 1 -121.9309 -121.9703       95050 Santa Clara          Santa Clara County
#   administrative_area_level_1       country
# 1                  California United States