我想在 R 中创建一个网络连接世界地图。我有一个节点的经度和纬度,但我只有另一个节点的城市和州/国家。ggplot 或 RGoogleMaps 仍然可以使用它吗?我应该怎么办?我在 Windows 中工作。
1 回答
If you have the city and state/country for the other node, you can get the longitude and latitude using the Googlemaps API in Python. Suppose you have your list of city names in a CSV file, then you can just loop through them one at a time, retrieving the longitude and latitude and writing it to a new file. The results can then be loaded into R as a data frame.
Here is the sample Python code:
from googlemaps import GoogleMaps
import csv
ifile=csv.reader(open('CapitalCities.csv','rb'),delimiter=',')
ofile=open('CapCoordinates.csv','wb')
w=csv.writer(ofile,delimiter=',')
w.writerow(['Name','State','Latitude','Longitude'])
gmaps=GoogleMaps(API_KEY)
count=0
for row in ifile:
if count!=0:
address=str(row[0])+" "+str(row[1])
lat, lng = gmaps.address_to_latlng(address)
w.writerow([str(row[0]),str(row[1]),str(lat),str(lng)])
print row[0],lat,lng
count+=1
ofile.close()
There are also methods for doing the same thing in R. A quick read of this post might prove useful: http://forgetfulfunctor.blogspot.com.au/2012/02/undiscovered-country-tutorial-on.html