Related
I am trying to obtain a map of a part of London (England) using the ggmap package in R, coordinates -0.205, 51.516. However, when obtaining/plotting the map, the centre constantly defaults to 29.763284,-95.36327 (somewhere in Houston, Texas). For example, see the structure of the link below - nb: it's not navigable without a valid API key.
Source : https://maps.googleapis.com/maps/api/staticmap?center=29.763284,-95.363271&zoom=16&size=640x640&scale=2&maptype=satellite&key=[xxx-last_part_of_my_API_key]
I've tried to use alternative coordinates but the result is always the same. Have also tried to use an alternative API keys to no avail. My stripped down code is as follows:
library(ggmap)
register_google(key = "[my API key]")
has_google_key()
test <- get_googlemap(location = c(lon=-0.205, lat=51.516),
zoom = 16, maptype = "satellite",color="bw")
ggmap(test)
The expected result is that centre will update to -0.205, 51.516 and show a portion of Portobello Road as a black and white Satellite Google map tile. Suggestions and comments are most welcome - go easy, I'm new here! Apologies if this question has already been asked/addressed.
I think it should be center instead of location.
test <- get_googlemap(center = c(lon=-0.205, lat=51.516),
zoom = 16, maptype = "satellite",color="bw")
The default values are center = c(lon = -95.3632715, lat = 29.7632836), which is downtown Houston.
I am trying to use GeoPandas for a (only slightly) more complex project, but at the moment I'm failing to write out a simple shapefile with a single point in it in a projected manner.
The following code results in a shapefile that looks generally good - but the .prj is empty:
import pandas as pd
from geopandas import GeoDataFrame
from shapely.geometry import Point
df=pd.read_csv("richmond.csv")
geometry = [Point(xy) for xy in zip(df.x, df.y)]
crs = {'init': 'epsg:4326'}
geo_df = GeoDataFrame(df, crs=crs, geometry=geometry)
geo_df.to_file("geopan.shp")
The csv is 2 row and 2 columns (header row, then lon and lat in 2nd row):
Am I missing something obvious? I've hunted through stackoverflow, the geopandas docs, etc. All seem to imply to_file() should work just fine.
In the long run, the goal is to create a few functions for my students to use in a lab - one that draws a line along a lat or lon the width / height of the US, another that clips the line to polygons (the states), so that the students can figure out the widest spot in each state as a gentle introduction to working with spatial data. I'm trying to avoid arcpy as it's Python 2, and I thought (and think) I was doing the right thing by teaching them the ways of Python 3. I'd like them to be able to debug their methodologies by being able to open the line in Arc though, hence this test.
So, after playing with this, I've determined that under the current version of Anaconda the problem is with crs = {'init': 'epsg:4326'} on Windows machines. This works fine on Macs, but has not worked on any of my or my students' Windows systems. Changing this line to make use of the proj4 string crs = {'proj': 'latlong', 'ellps': 'WGS84', 'datum': 'WGS84', 'no_defs': True} instead works just fine. More of a workaround than an actual solution, but, it seems to consistently work.
I'm always using from_epsg function from fiona library.
>>> from fiona.crs import from_epsg
>>> from_epsg(4326)
{'init': 'epsg:4326', 'no_defs': True}
I've never had any problems using it. Keep it mind that some local projections are missing, but it shouldn't be a problem in your case.
Another user and I had a similar issue using fiona, and the issue for me was the GDAL_DATA environmental variable not being set correctly. To reiterate my answer there: For reference, I'm using Anaconda, the Spyder IDE, Fiona 1.8.4, and Python 3.6.8, and GDAL 2.3.3.
While Anaconda usually sets the GDAL_DATA variable upon entering the virtual environment, using another IDE like Spyder will not preserve it, and thus causes issues where fiona (and I assume Geopandas) can't export the CRS correctly.
You can test this fix by trying to printing out a EPSG to WKT transformation before & after setting the GDAL_DATA variable explictly.
Without setting GDAL_DATA:
import os
print('GDAL_DATA' in os.environ)
from osgeo import osr
srs = osr.SpatialReference() # Declare a new SpatialReference
srs.ImportFromEPSG(3413) # Import the EPSG code into the new object srs
print(srs.ExportToWkt()) # Print the result before transformation to ESRI WKT (prints nothing)
Results in:
False
With setting GDAL_DATA:
import os
os.environ['GDAL_DATA'] = 'D:\\ProgramData\\Anaconda3\\envs\\cfm\\Library\\share\\gdal'
print('GDAL_DATA' in os.environ)
from osgeo import , osr
srs = osr.SpatialReference() # Declare a new SpatialReference
srs.ImportFromEPSG(3413) # Import the EPSG code into the new object srs
print(srs.ExportToWkt()) # Print the result before transformation to ESRI WKT (prints nothing)
Results in:
True
PROJCS["WGS 84 / NSIDC Sea Ice Polar Stereographic North",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Polar_Stereographic"],PARAMETER["latitude_of_origin",70],PARAMETER["central_meridian",-45],PARAMETER["scale_factor",1],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["X",EAST],AXIS["Y",NORTH],AUTHORITY["EPSG","3413"]]
I'm trying to use the geocode function from the ggmaps library in R to get coordinates for specific locations. I'm able to use the function fine so far.
The issue I'm running into is that I would like to increase my daily limit from 2,500 to 100,000. The official Google documentation
says that this is readily possible if you enable billing on the project, which I'm happy to do. When you proceed with this process, the Google Developers Console gives you a personalized API key.
However, the geocode function doesn't have an option to put in this personalized API key. Instead, it asks for the client (client ID for business users) and signature(signature for business users), which is how Google Maps API for Work customers can access the API. I get that this is also an option, but that seems to be a very use case, since Google Maps API for Work seems to be designed for large enterprise accounts:
Daily quota starting at 100,000 requests per 24 hours, based on annual contractual purchase.
So my question boils down to this: can I use the geocode function from the ggmapslibrary in R to ping the Google Maps Geocoding API?
With ggmap version 2.7 or greater (as of 13 Dec, not yet available on Cran, but you can install with devtools::install_github("dkahle/ggmap"), you simply need to run register_google(key = 'LONG KEY STRING') and then you can call any of the ggmap functions such as geocode or mutate_geocode and use your API key.
I've written the package googleway to access google maps API where you can specify your api key.
For example
library(googleway)
key <- "your_api_key"
google_geocode(address = "San Francisco",
key = key)
# $results
# address_components
# 1 San Francisco, San Francisco County, California, United States, SF, San Francisco County, CA, US, locality, political, administrative_area_level_2, political, administrative_area_level_1, political, country, political
# formatted_address geometry.bounds.northeast.lat geometry.bounds.northeast.lng geometry.bounds.southwest.lat
# 1 San Francisco, CA, USA 37.92977 -122.3279 37.69313
# geometry.bounds.southwest.lng geometry.location.lat geometry.location.lng geometry.location_type
# 1 -123.1661 37.77493 -122.4194 APPROXIMATE
# geometry.viewport.northeast.lat geometry.viewport.northeast.lng geometry.viewport.southwest.lat
# 1 37.812 -122.3482 37.7034
# geometry.viewport.southwest.lng place_id types
# 1 -122.527 ChIJIQBpAG2ahYAR_6128GcTUEo locality, political
#
# $status
# [1] "OK"
Thanks for this! It helped me along immensely.
Your solution is pretty specific, so I wanted to include the adaptations I made of your function. It threw bugs because raw_data and geo_data_list are undefined. I'm guessing these were specific to your local environment.
For me, inputting a location and returning the lat, lon worked with this:
getGeoData <- function(location, api_key){
location <- gsub(' ','+',location)
geo_data <- getURL(paste("https://maps.googleapis.com/maps/api/geocode/json?address=",location,sprintf("&key=%s",api_key), sep=""))
geo_data <- fromJSON(geo_data)
return(geo_data$results[[1]]$geometry$location)
}
You can modify the return statement to index into geo_data to get different properties other than lat lon too.
Hope this helps someone.
R
I didn't find a way to use the existing geocode function (from the ggmap library) to answer this question, so I just created a new function to just do this myself using the existing getURL function (from the RCurl library) and the fromJSON function (from the RJSONIO library).
Write the new function:
library(RJSONIO)
library(RCurl)
getGeoData <- function(location){
location <- gsub(' ','+',location)
geo_data <- getURL(paste("https://maps.googleapis.com/maps/api/geocode/json?address=",location,"&key=**[YOUR GOOGLE API KEY HERE]**", sep=""))
raw_data_2 <- fromJSON(geo_data)
return(raw_data_2)
}
Test:
getGeoData("San Francisco")
This gives you a list with the same data that's almost (but not quite) in the same exact format as the list produced by geocode("San Francisco").
I'm looking to import a Google API static map into R using the GetMap function of the RGoogleMaps package. I then plan to plot data points onto the graph in R using PlotOnStaticMap. I would like to use the "terrain" maptype, but don't want the labels on it. I have found a previous stackoverflow question that addresses how to remove the labels on the map by using "style=feature:all|element:labels|visibility:off".
Map with labels: (http://maps.googleapis.com/maps/api/staticmap?center=29.4,-89.2&zoom=9&size=600x500&maptype=terrain&sensor=false)
Map without labels: (http://maps.googleapis.com/maps/api/staticmap?center=29.4,-89.2&zoom=9&size=600x500&maptype=terrain&sensor=false&style=feature:all|element:labels|visibility:off)
This second code produces the exact map I would like. However, when I save it as a PNG file and then go to import it into R using the GetMaps function, it gives me the original map with all the labels still attached.
Does anyone know how I can get the map without labels imported correctly into R? It seems like it shouldn't be that hard, but I haven't been able to come up with a solution.
Thanks!
Codes in R:
smap<-read.table("D:/sediment/Rfiles/smap.txt", header=TRUE, sep= "");
library(RgoogleMaps)
library(rgdal)
MyMap <- GetMap(center=c(29.4, -89.2), zoom=9,
destfile = "D:/sediment/Rfiles/map.png", maptype="terrain")
map<-PlotOnStaticMap(MyMap, lat=smap$lat, lon=smap$lon,
col=c('black'), add=F,cex=1.1,pch=19)
*smap is a data file of lat, lon coordinates to be plotted on the map
Like this?
MyMap <- GetMap(center=c(29.4, -89.2), zoom=9,
destfile = "D:/sediment/Rfiles/map.png", maptype="terrain",
path = "&style=feature:all|element:labels|visibility:off")
I want to create a network connection world map in R. I have the longitude and
latitude for one node but I only have the city and state/country for the
other node. Can ggplot or RGoogleMaps still work with this? What should I do?
I am working in Windows.
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