Skip to content

Instantly share code, notes, and snippets.

@geotheory
Last active October 10, 2021 01:36
Show Gist options
  • Save geotheory/7103991 to your computer and use it in GitHub Desktop.
Save geotheory/7103991 to your computer and use it in GitHub Desktop.
KML to GeoJSON conversion in R
#########################################################
##### Script to load in KML and output to GeoJSON #####
##### Robin Edwards, geotheory.co.uk, @geotheory #####
#########################################################
# This script accepts a simple KML file (e.g. from Google Earth or Scribblemaps.com) and converts to GeoJSON.
# It will not accept KMLs with multiple geometries - they must be entirely of points, paths or polygons,
# or a primitive geometry (such as rectangle or circle)
#
# How to run:
# - update the working directory path in the setwd() below to the script's parent folder
# - copy the KML file you want to convert to the same folder and rename it 'data.kml'
# - navigate to folder in OSX Console / Windows command prompt / etc
# - type 'RScript kml_to_geojson.R'
# - a file named 'data.geojson' will be writted (overwritten if already exists)
#
# If RScript fails to run in Windows you may need to add its executable folder path to the 'PATH' list
# in Environmental Variables.
require(rgdal)
require(stringr)
setwd('C:/Folder Path') # UPDATE TO SCRIPT FOLDER
map = readOGR("data.kml", layer=ogrListLayers("data.kml"), verbose=T,
drop_unsupported_fields=T, dropNULLGeometries=T, stringsAsFactors=F)
# removes HTML code that can appear in Description field (e.g. scribblemaps)
if(any(str_detect(map@data[,2], "<FONT"))){
try(map@data[,2] <- str_match(map@data[,2], "<FONT.*>(.*)</FONT>")[,2], silent=T)
}
unlink("data.geojson")
writeOGR(map, "data.geojson", "data", driver = "GeoJSON")
@pnear
Copy link

pnear commented Sep 2, 2015

For anyone using this converter, you need to modify the writeOGR function to this:

writeOGR(map, "data.geojson", "data", driver = "GeoJSON", check_exists = FALSE)

By adding: check_exist = FALSE , you can avoid the "Cannot Open File" error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment