2016-01-22 77 views
2

我需要在R中搜索特定座標的細節。假設我的座標是:25.34926,51.47819。我使用nominatim來解析關於特定座標的細節。在R中解析XML輸出,打開街道地圖數據

query <- sprintf("http://nominatim.openstreetmap.org/reverse?format=xml& lat=%s&lon=%s",lat,lon) 

result <- GET(query) 
xml <- content(result, 'parsed') 
list_xml = xmlToList(xml) 

place_id = list_xml$result$.attrs["osm_id"] 
place_id = as.numeric(place_id) 
type = list_xml$result$.attrs["osm_type"] 
type = as.character(type) 

我得到了道路的類型和使用這些代碼的唯一ID。現在,我傳遞這些參數來獲取有關位置的詳細信息。

query <- sprintf("http://www.openstreetmap.org/api/0.6/%s/%s",type,place_id) 

結果< - GET(查詢) XML < - 內容(結果, '解析')

這是XML輸出,

<?xml version="1.0" encoding="UTF-8"?> 
<osm version="0.6" generator="CGImap 0.4.0 (5500 thorn-02.openstreetmap.org)" copyright="OpenStreetMap and contributors" attribution="http://www.openstreetmap.org/copyright" license="http://opendatacommons.org/licenses/odbl/1-0/"> 

<way id="25935530" visible="true" version="8" changeset="25997075" timestamp="2014-10-11T06:26:45Z" user="Kostik" uid="384084"> 
<nd ref="2012765518"/> 
<nd ref="2012765515"/> 
<nd ref="1138152548"/> 
<nd ref="1138151957"/> 
<nd ref="1138152112"/> 
<nd ref="1138152995"/> 
<nd ref="1885503851"/> 
<nd ref="1138152065"/> 
<nd ref="282906579"/> 
<nd ref="282905674"/> 
<nd ref="282905676"/> 
<nd ref="282905677"/> 
<nd ref="282905678"/> 
<nd ref="282905679"/> 
<nd ref="1684400272"/> 
<nd ref="1684400191"/> 
<nd ref="282906298"/> 
<nd ref="1138152685"/> 
<nd ref="1138152719"/> 
<nd ref="1138151621"/> 
<tag k="highway" v="primary"/> 
<tag k="name" v="Al Khafaji Street"/> 
<tag k="oneway" v="yes"/> 
</way> 
</osm> 

我關心<tag>標籤,我如何獲取價值?我使用下面提到的代碼,但是我很難解析它。我非常瘋狂地搜查,但無濟於事。

list_xml = xmlToList(xml) 
tr <- getNodeSet(xml, "//osm/way/tags") 
+1

https://github.com/hrbrmstr/nominatim – hrbrmstr

+0

它在R中的osmar包中起作用 –

回答

0

解決了!我在R中下載了'osmar'包,並使用下面的代碼 - 我可以獲取所需的值。

query <- sprintf("http://www.openstreetmap.org/api/0.6/%s/%s",type,place_id) 
    result <- GET(query) 
    xml <- content(result, 'parsed') 
    osm = as_osmar(xml) 

    if(type == "way") { 
    w <- way(osm) 
    t <- w$ways$tags 
    } else { 
    if(type == "node") { 
     n <- node(osm) 
     t <- n$nodes$tags 
    } else { 
     r <- relation(osm) 
     t <- r$relations$tags  
    } 
    } 

    for(j in 1:nrow(t)){ 
    #print(as.character(t[j,2])) 
    if(as.character(t[j,2]) %in% colnames(features)){ 
     colNumber = which(colnames(features) == as.character(t[j,2])) 
     if(as.character(t[j,3]) == '0'){ 
     features[i, colNumber] = 'Not Defined' 
     } 
     else{ 
     features[i, colNumber] = as.character(t[j,3]) 
     } 
     # 
    } 
    #else{ 
    # if(as.character(t[j,2]) != 'name:en' && as.character(t[j,2]) != 'name:ar' && as.character(t[j,2]) != 'cuisine' && as.character(t[j,2]) != 'ref' && as.character(t[j,2]) != 'source'){ 
    #  rest <- sprintf("lat=%s&lon=%s,%s",lat,lon,as.character(t[j,2])) 
      #print(rest)  
    # } 
    #} 
    }