Created
July 13, 2017 11:57
-
-
Save rvosa/e920a2d7af22ac258c58344eb2d74f25 to your computer and use it in GitHub Desktop.
How to query the Google Maps API for geo-referencing using R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 2.2 Georeferecing with Google API | |
# Has a maximum of 2500 requests per day (error: You have exceeded your daily request quota for this API) | |
rm(list = ls(all=T)) | |
unique.Geodata <- read.csv('Datasets/unique.Geodata.csv', h=T) | |
head(unique.Geodata) | |
dim(unique.Geodata) # 22132 10 | |
str(unique.Geodata) | |
unique.Geodata$LongitudeDD <- as.character(unique.Geodata$LongitudeDD) | |
unique.Geodata$LatitudeDD <- as.character(unique.Geodata$LatitudeDD) | |
unique.Geodata$Geodata <- as.character(unique.Geodata$Geodata) | |
str(unique.Geodata) | |
library(sp) | |
library(raster) | |
library(XML) | |
library(dismo) | |
# Try some names | |
try(geocode('Malaysia/Malaya; Batu Puteh; ')) | |
try(geocode('Vietnam, Hon Ba')) | |
try(geocode('Ban-chiou-chian, Che-li Hsien, Yunnan, Jinghong, China, Asia')) | |
geocode('Che-li Hsien, Yunnan, Jinghong, China, Asia') | |
geocode("Jardin d'expérience de Collioure, de l'intérieure de l'Afrique, Namibia") | |
geocode('Jardin d expérience de Collioure, de l intérieure de l Afrique, Namibia') | |
# Replace coordinates with Google coordinates if accuracy is within uncertainty | |
uncertainty <- 10000 # in meters (= 10km) | |
for(j in 1:nrow(unique.Geodata)){ | |
#for(j in 778:nrow(unique.Geodata)){ | |
Sys.sleep(0.5) # wait 0.5 seconds | |
b <- geocode(unique.Geodata$Geodata[j]) | |
print(j) | |
b2 <- subset(b, b$uncertainty == min(b$uncertainty)) # select record with least uncertainty | |
if(dim(b2)[1] == 0){ | |
unique.Geodata[j, 'LatitudeDD'] <- unique.Geodata[j, 'LatitudeDD'] #; print(1) | |
unique.Geodata[j, 'LongitudeDD'] <- unique.Geodata[j, 'LongitudeDD'] #; print('a') | |
} else { | |
b2 <- b2[1,] # sometimes 2 same minimum values i.e. geocode('Austria,Niederoesterreich,Weinviertel,Katzelsdorf') | |
if(b2[, 'uncertainty'] < uncertainty) { | |
unique.Geodata[j, 'LatitudeDD'] <- b2[, 'latitude'] | |
unique.Geodata[j, 'LongitudeDD'] <- b2[, 'longitude'] | |
unique.Geodata[j, 'coordUncertaintyM'] <- b2[, 'uncertainty'] | |
} else { | |
unique.Geodata[j, 'LatitudeDD'] <- unique.Geodata[j, 'LatitudeDD'] | |
unique.Geodata[j, 'LongitudeDD'] <- unique.Geodata[j, 'LongitudeDD'] | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment