[英]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.