[英]How to get the longitude and latitude coordinates from a city name and country in 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
,它使用谷歌地圖進行地理編碼。 這限制你每天2,500。
taRifx.geo
taRifx.geo的最新版本具有geocode
功能,可使用Google或Bing Maps進行地理編碼。 Bing版本要求您使用(免費)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);
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.