Skip to content

Instantly share code, notes, and snippets.

@FrieseWoudloper
Last active February 9, 2016 14:57
Show Gist options
  • Save FrieseWoudloper/2b7a6b88bc7729b903c4 to your computer and use it in GitHub Desktop.
Save FrieseWoudloper/2b7a6b88bc7729b903c4 to your computer and use it in GitHub Desktop.
R-script voor het downloaden en converteren van een JSON-bestand met locaties van jachthavens converteren naar shape-bestand
library(httr)
library(jsonlite)
library(XML)
library(sp)
library(rgdal)
###########################
# Downloaden JSON-bestand #
###########################
r <- POST('http://toerisme.groningen.nl/over-groningen/groningen-op-de-kaart/zoeken?q=+Zoeken+op+woord,+bedrijfsnaam+of+plaats+&plaats=&branches[]=238',
add_headers(`X-Requested-With` = "XMLHttpRequest"))
# branche = 191 -> hotels
# branche = 3308 -> B&B
# branche = 200 -> hostels
stop_for_status(r) # Converteer indien van toepassing HTTP fout of waarschuwing naar R
x <- content(r, "parsed", "application/json")
########################
# Inlezen JSON-bestand #
########################
getValue1 <- function(label){
for (j in 1:length(content)){
if (length(content[[j]]) > 0) {if (regexpr(label, content[[j]]) > 0) return (sub(label, "", content[[j]]))}
}
return ("")
}
getValue2 <- function(label) {
for (j in 1:(length(content)-1)){
if (length(content[[j]]) > 0) {if (content[[j]] == label) return (content[[j+1]])}
}
return ("")
}
df <- data.frame()
for (i in 1:length(x)) {
brancheid <- x[[i]]$brancheid
gidsvermelding <- x[[i]]$gidsvermelding
latitude <- x[[i]]$latitude
longitude <- x[[i]]$longitude
xmlnodes <- xmlTreeParse(x[[i]]$html)
rootnode <- xmlRoot(xmlnodes)
naam <- xmlValue(rootnode[[c("h3")]])
content <- xmlSApply(rootnode[[c('p')]], xmlValue)
adres <- content[[1]]
postcode <- substr(content[[3]], 1, 7)
plaats <- substr(content[[3]], 9, nchar(content[[3]]))
telefoon <- getValue1("T: ")
fax <- getValue1("F: ")
website <- getValue2("Website:")
email <- getValue2("E:")
df <- rbind(df, data.frame(brancheid, gidsvermelding, latitude, longitude, naam, adres, postcode, plaats, telefoon, fax, website, email, stringsAsFactors = FALSE))
}
##############################
# Exporteren naar shape-file #
##############################
colnames(df) = c("branche", "gidsvrm", "lat", "lon", "naam", "adres", "pc", "plaats", "tel", "fax", "web", "email") # Korte namen i.v.m. export naar shape-file
punten_wgs84 <- SpatialPointsDataFrame(df[, c('lon', 'lat')], df, proj4string = CRS("+proj=longlat"))
punten_rd <- spTransform(punten_wgs84, CRS("+init=epsg:28992"))
writeOGR(punten_rd, dsn = "d:/temp", layer = "jachthavens", driver = "ESRI Shapefile")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment