我尝试编写一个简单的代码来检查街道地址是否存在:
在我的第一次尝试中,我输入正确的地址并得到了正确的地址:
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值或某个标志?