我有一長串的城市名稱和國家,我想在地圖上繪製它們。爲了做到這一點,我需要每個城市的經度和緯度信息。如何從R中的城市名稱和國家獲取經度和緯度座標?
我的表稱爲test
並具有以下結構:
Cityname CountryCode
New York US
Hamburg DE
Amsterdam NL
我有一長串的城市名稱和國家,我想在地圖上繪製它們。爲了做到這一點,我需要每個城市的經度和緯度信息。如何從R中的城市名稱和國家獲取經度和緯度座標?
我的表稱爲test
並具有以下結構:
Cityname CountryCode
New York US
Hamburg DE
Amsterdam NL
用下面的代碼,我已經成功地解決了這個問題。
library(RJSONIO)
nrow <- nrow(test)
counter <- 1
test$lon[counter] <- 0
test$lat[counter] <- 0
while (counter <= nrow){
CityName <- gsub(' ','%20',test$CityLong[counter]) #remove space for URLs
CountryCode <- test$Country[counter]
url <- paste(
"http://nominatim.openstreetmap.org/search?city="
, CityName
, "&countrycodes="
, CountryCode
, "&limit=9&format=json"
, sep="")
x <- fromJSON(url)
if(is.vector(x)){
test$lon[counter] <- x[[1]]$lon
test$lat[counter] <- x[[1]]$lat
}
counter <- counter + 1
}
由於這是調用外部服務(openstreetmaps.org),對於較大的數據集可能需要一段時間。但是,您可能只會在新城市已添加到列表中時偶爾會這樣做。
其他一些選項適合你。
ggmaps
ggmaps具有功能geocode
它使用谷歌地圖進行地理編碼。這限制你每天2500。
taRifx.geo
taRifx.geo的最新版本有一個geocode
功能,使用谷歌或Bing地圖進行地理編碼。必應版本要求您使用(免費)必應賬戶,但作爲回報,您可以通過地理編碼方式輸入更多條目。在這個版本的特點:
試試這個我覺得對於這個問題
> library(ggmap)
Loading required package: ggplot2
Google Maps API Terms of Service: http://developers.google.com/maps/terms.
Please cite ggmap if you use it: see citation('ggmap') for details.
#Now you can give city name or country name individually
> geocode("hamburg")
Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=hamburg&sensor=false
lon lat
1 9.993682 53.55108
geocode("amsterdam")
Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=amsterdam&sensor=false
lon lat
1 4.895168 52.37022
> geocode("new york")
Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=new+york&sensor=false
lon lat
1 -74.00594 40.71278
它會更好的解決辦法試試這個...
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location,
draggable:true
});
var infowindow = new google.maps.InfoWindow({
content: "Please drag this marker to your position.."
});
infowindow.open(resultsMap,marker);
document.getElementById('lat').value=marker.getPosition().lat();
document.getElementById('lng').value=marker.getPosition().lng();
marker.addListener('drag', handleEvent);
marker.addListener('dragend', handleEvent);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
您也可以使用我的geonames軟件包中的GNsearch做到這一點 - 它調用geonames.org網絡服務,該服務與OpenStreetMap的Nominatim服務共享大量數據。 – Spacedman
@Jochem我如何做到這一點?我有經度和緯度,我需要像上面那樣通過json格式使用開放街道來查找城市和鄉村名稱? –