• Stars
    star
    166
  • Rank 227,748 (Top 5 %)
  • Language
    R
  • License
    GNU General Publi...
  • Created over 5 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Download and import OpenStreetMap data from Geofabrik and other providers

osmextract

R build status Codecov test coverage peer-review Project Status: Active – The project has reached a stable, usable state and is being actively developed. CRAN status

The goal of osmextract is to make it easier for people to access OpenStreetMap (OSM) data for reproducible research. OSM data is the premier source of freely available, community created geographic data worldwide. We aim to enable you to extract it for data-driven work in the public interest.

osmextract matches, downloads, converts and imports bulk OSM data hosted by providers such as Geofabrik GmbH and bbbike. For information on alternative providers and how to add them see the providers vignette.

Why osmextract?

The package answers a common question for researchers who use OSM data: how to get it into a statistical environment, in an appropriate format, as part of a computationally efficient and reproducible workflow? Other packages answer parts of this question. osmdata, for example, is an R package that provides an R interface to the Overpass API, which is ideal for downloading small OSM datasets. However, the API is rate limited, making it hard to download large datasets. As a case study, try to download all cycleways in England using osmdata:

library(osmdata)
cycleways_england = opq("England") %>% 
  add_osm_feature(key = "highway", value = "cycleway") %>% 
  osmdata_sf()
# Error in check_for_error(doc) : General overpass server error; returned:
# The data included in this document is from www.openstreetmap.org. The data is made available under ODbL. runtime error: Query timed out in "query" at line 4 after 26 seconds. 

The query stops with an error message after around 30 seconds. The same query can be made with osmextract as follows, which reads-in almost 100k linestrings in less than 10 seconds, after the data has been downloaded in the compressed .pbf format and converted to the open standard .gpkg format. The download-and-conversion operation of the OSM extract associated to England takes approximately a few minutes, but this operation must be executed only once. The following code chunk is not evaluated.

library(osmextract)

cycleways_england = oe_get(
  "England",
  quiet = FALSE,
  query = "SELECT * FROM 'lines' WHERE highway = 'cycleway'"
)
par(mar = rep(0.1, 4))
plot(sf::st_geometry(cycleways_england))

The package is designed to complement osmdata, which has advantages over osmextract for small datasets: osmdata is likely to be quicker for datasets less than a few MB in size, provides up-to-date data and has an intuitive interface. osmdata can provide data in a range of formats, while osmextract only returns sf objects. osmextract’s niche is that it provides a fast way to download large OSM datasets in the highly compressed pbf format and read them in via the fast C library GDAL and the popular R package for working with geographic data sf.

Installation

You can install the released version of osmextract from CRAN with:

install.packages("osmextract")

You can install the development version from GitHub with:

# install.packages("remotes")
remotes::install_github("ropensci/osmextract")

Load the package with:

library(osmextract)
#> Data (c) OpenStreetMap contributors, ODbL 1.0. https://www.openstreetmap.org/copyright.
#> Check the package website, https://docs.ropensci.org/osmextract/, for more details.

To use alongside functionality in the sf package, we also recommend attaching this geographic data package as follows:

library(sf)
#> Linking to GEOS 3.11.2, GDAL 3.6.2, PROJ 9.2.0; sf_use_s2() is TRUE

Warnings:

The functions defined in this package may return a warning message like

st_crs<- : replacing crs does not reproject data; use st_transform for that 

if the user is running an old version of GDAL (<= 3.0.0) or PROJ (<= 6.0.0). See here for more details. Nevertheless, every function should still work correctly. Please, raise a new issue if you find any odd behaviour.

Basic usage

Give osmextract a place name and it will try to find it in a list of names in the specified provider (Geofabrik by default). If the name you give it matches a place, it will download and import the associated data into R. The function oe_get() downloads (if not already downloaded) and reads-in data from OSM providers as sf objects. By default oe_get() imports the lines layer, but any layer can be read-in by changing the layer argument:

osm_lines = oe_get("Isle of Wight", stringsAsFactors = FALSE, quiet = TRUE)
osm_points = oe_get("Isle of Wight", layer = "points", stringsAsFactors = FALSE, quiet = TRUE)
nrow(osm_lines)
#> [1] 51226
nrow(osm_points)
#> [1] 67783
par(mar = rep(0, 4))
plot(st_geometry(osm_lines), xlim = c(-1.59, -1.1), ylim = c(50.5, 50.8))
plot(st_geometry(osm_points), xlim = c(-1.59, -1.1), ylim = c(50.5, 50.8))

The figures above give an insight into the volume and richness of data contained in OSM extracts. Even for a small island such as the Isle of Wight, it contains over 50k features including ferry routes, shops and roads. The column names in the osm_lines object are as follows:

names(osm_lines) # default variable names
#>  [1] "osm_id"     "name"       "highway"    "waterway"   "aerialway" 
#>  [6] "barrier"    "man_made"   "z_order"    "other_tags" "geometry"

Once imported, you can use all functions for data frames in base R and other packages. You can also use functions from the sf package for spatial analysis and visualisation. Let’s plot all the major, secondary and residential roads, for example:

ht = c("primary", "secondary", "tertiary", "unclassified") # highway types of interest
osm_major_roads = osm_lines[osm_lines$highway %in% ht, ]
plot(osm_major_roads["highway"], key.pos = 1)

The same steps can be used to get other OSM datasets (examples not run):

malta = oe_get("Malta", quiet = TRUE)
andorra = oe_get("Andorra", extra_tags = "ref")
leeds = oe_get("Leeds")
goa = oe_get("Goa", query = "SELECT highway, geometry FROM 'lines'")

If the input place does not match any of the existing names in the supported providers, then oe_get() will try to geocode it via Nominatim API, and it will select the smallest OSM extract intersecting the area. For example (not run):

oe_get("Milan") # Warning: It will download more than 400MB of data
#> No exact match found for place = Milan and provider = geofabrik. Best match is Iran.
#> Checking the other providers.
#> No exact match found in any OSM provider data. Searching for the location online.
#> ... (extra messages here)

For further details on using the package, see the Introducing osmextract vignette.

Persistent download directory

The default behaviour of oe_get() is to save all the files in a temporary directory, which is erased every time you restart your R session. If you want to set a directory that will persist, you can add OSMEXT_DOWNLOAD_DIRECTORY=/path/for/osm/data in your .Renviron file, e.g.Β with:

usethis::edit_r_environ()
# Add a line containing: OSMEXT_DOWNLOAD_DIRECTORY=/path/to/save/files

We strongly advise you setting a persistent directory since working with .pbf files is an expensive operation, that is skipped by oe_*() functions if they detect that the input .pbf file was already downloaded.

You can always check the default download_directory used by oe_get() with:

oe_download_directory()

Next steps

We would love to see more providers added (see the Add new OpenStreetMap providers for details) and see what people can do with OSM datasets of the type provided by this package in a reproducible and open statistical programming environment for the greater good. Any contributions to support this or any other improvements to the package are very welcome via our issue tracker.

Licence

We hope this package will provide easy access to OSM data for reproducible research in the public interest, adhering to the condition of the OdBL licence which states that

Any Derivative Database that You Publicly Use must be only under the terms of:

    1. This License;
    1. A later version of this License similar in spirit to this

See the Introducing osmextract vignette for more details.

Other approaches

  • osmdata is an R package for importing small datasets directly from OSM servers
  • geofabrik is an R package to download OSM data from Geofabrik
  • pyrosm is a Python package for reading .pbf files
  • pydriosm is a Python package to download, read and import OSM extracts
  • osmium provides python bindings for the Libosmium C++ library
  • OpenStreetMapX.jl is a Julia package for reading and analysing .osm files
  • PostGIS is an established spatial database that works well with large OSM datasets
  • Any others? Let us know!

Contribution

We very much look forward to comments, questions and contributions. If you have any question or if you want to suggest a new approach, feel free to create a new discussion in the github repository. If you found a bug, or if you want to add a new OSM extracts provider, create a new issue in the issue tracker or a new pull request. We always try to build the most intuitive user interface and write the most informative error messages, but if you think that something is not clear and could have been explained better, please let us know.

Contributor Code of Conduct

Please note that this package is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.

More Repositories

1

drake

An R-focused pipeline toolkit for reproducibility and high-performance computing
R
1,339
star
2

skimr

A frictionless, pipeable approach to dealing with summary statistics
HTML
1,108
star
3

targets

Function-oriented Make-like declarative workflows for R
R
912
star
4

rtweet

🐦 R client for interacting with Twitter's [stream and REST] APIs
R
785
star
5

tabulizer

Bindings for Tabula PDF Table Extractor Library
R
518
star
6

pdftools

Text Extraction, Rendering and Converting of PDF Documents
C++
489
star
7

magick

Magic, madness, heaven, sin
R
440
star
8

visdat

Preliminary Exploratory Visualisation of Data
R
439
star
9

stplanr

Sustainable transport planning with R
R
417
star
10

RSelenium

An R client for Selenium Remote WebDriver
R
332
star
11

rnoaa

R interface to many NOAA data APIs
R
328
star
12

osmdata

R package for downloading OpenStreetMap data
R
315
star
13

charlatan

Create fake data in R
R
291
star
14

software-review

rOpenSci Software Peer Review.
R
279
star
15

iheatmapr

Complex, interactive heatmaps in R
R
259
star
16

taxize

A taxonomic toolbelt for R
R
250
star
17

rrrpkg

Use of an R package to facilitate reproducible research
248
star
18

elastic

R client for the Elasticsearch HTTP API
R
244
star
19

tesseract

Bindings to Tesseract OCR engine for R
R
236
star
20

git2r

R bindings to the libgit2 library
R
216
star
21

qualtRics

Download ⬇️ Qualtrics survey data directly into R!
R
215
star
22

biomartr

Genomic Data Retrieval with R
R
212
star
23

writexl

Portable, light-weight data frame to xlsx exporter for R
C
202
star
24

googleLanguageR

R client for the Google Translation API, Google Cloud Natural Language API and Google Cloud Speech API
HTML
194
star
25

rnaturalearth

An R package to hold and facilitate interaction with natural earth map data 🌍
R
191
star
26

textreuse

Detect text reuse and document similarity
R
188
star
27

piggyback

πŸ“¦ for using large(r) data files on GitHub
R
182
star
28

tokenizers

Fast, Consistent Tokenization of Natural Language Text
R
179
star
29

rentrez

talk with NCBI entrez using R
R
178
star
30

rcrossref

R client for various CrossRef APIs
R
166
star
31

dataspice

🌢️ Create lightweight schema.org descriptions of your datasets
R
159
star
32

rgbif

Interface to the Global Biodiversity Information Facility API
R
155
star
33

tic

Tasks Integrating Continuously: CI-Agnostic Workflow Definitions
R
153
star
34

webchem

Chemical Information from the Web
R
149
star
35

geojsonio

Convert many data formats to & from GeoJSON & TopoJSON
R
148
star
36

tsbox

tsbox: Class-Agnostic Time Series in R
R
148
star
37

MODIStsp

An "R" package for automatic download and preprocessing of MODIS Land Products Time Series
R
147
star
38

ghql

GraphQL R client
R
145
star
39

DataPackageR

An R package to enable reproducible data processing, packaging and sharing.
R
145
star
40

dev_guide

rOpenSci Packages: Development, Maintenance, and Peer Review
R
141
star
41

osfr

R interface to the Open Science Framework (OSF)
R
140
star
42

jqr

R interface to jq
R
139
star
43

tarchetypes

Archetypes for targets and pipelines
R
130
star
44

osmplotr

Data visualisation using OpenStreetMap objects
R
130
star
45

opencv

R bindings for OpenCV
C++
130
star
46

ssh

Native SSH client in R based on libssh
C
126
star
47

RefManageR

R package RefManageR
R
114
star
48

ezknitr

Avoid the typical working directory pain when using 'knitr'
R
112
star
49

spocc

Species occurrence data toolkit for R
R
109
star
50

hunspell

High-Performance Stemmer, Tokenizer, and Spell Checker for R
C++
106
star
51

weathercan

R package for downloading weather data from Environment and Climate Change Canada
R
102
star
52

crul

R6 based http client for R (for developers)
R
102
star
53

UCSCXenaTools

πŸ“¦ An R package for accessing genomics data from UCSC Xena platform, from cancer multi-omics to single-cell RNA-seq https://cran.r-project.org/web/packages/UCSCXenaTools/
R
102
star
54

gistr

Interact with GitHub gists from R
R
101
star
55

spelling

Tools for Spell Checking in R
R
101
star
56

rfishbase

R interface to the fishbase.org database
R
100
star
57

gutenbergr

Search and download public domain texts from Project Gutenberg
R
99
star
58

git2rdata

An R package for storing and retrieving data.frames in git repositories.
R
99
star
59

openalexR

Getting bibliographic records from OpenAlex
R
98
star
60

bib2df

Parse a BibTeX file to a tibble
R
97
star
61

ckanr

R client for the CKAN API
R
97
star
62

nasapower

API Client for NASA POWER Global Meteorology, Surface Solar Energy and Climatology in R
R
96
star
63

rsvg

SVG renderer for R based on librsvg2
C
95
star
64

EML

Ecological Metadata Language interface for R: synthesis and integration of heterogenous data
R
94
star
65

FedData

Functions to Automate Downloading Geospatial Data Available from Several Federated Data Sources
R
94
star
66

cyphr

:shipit: Humane encryption
R
93
star
67

GSODR

API Client for Global Surface Summary of the Day (GSOD) Weather Data Client in R
R
90
star
68

mapscanner

R package to print maps, draw on them, and scan them back in
R
88
star
69

av

Working with Video in R
C
88
star
70

opencage

🌐 R package for the OpenCage API -- both forward and reverse geocoding 🌐
R
87
star
71

gittargets

Data version control for reproducible analysis pipelines in R with {targets}.
R
85
star
72

tidync

NetCDF exploration and data extraction
R
85
star
73

historydata

Datasets for Historians
R
83
star
74

rzmq

R package for ZMQ
C++
82
star
75

CoordinateCleaner

Automated flagging of common spatial and temporal errors in biological and palaeontological collection data, for the use in conservation, ecology and palaeontology.
HTML
79
star
76

rebird

Wrapper to the eBird API
R
79
star
77

smapr

An R package for acquisition and processing of NASA SMAP data
R
79
star
78

bikedata

🚲 Extract data from public hire bicycle systems
R
79
star
79

dittodb

dittodb: A Test Environment for DB Queries in R
R
78
star
80

arkdb

Archive and unarchive databases as flat text files
R
78
star
81

fingertipsR

R package to interact with Public Health England’s Fingertips data tool
R
78
star
82

vcr

Record HTTP calls and replay them
R
77
star
83

nodbi

Document DBI connector for R
R
76
star
84

opentripplanner

An R package to set up and use OpenTripPlanner (OTP) as a local or remote multimodal trip planner.
R
73
star
85

nlrx

nlrx NetLogo R
R
71
star
86

slopes

Package to calculate slopes of roads, rivers and trajectories
R
70
star
87

tidyhydat

An R package to import Water Survey of Canada hydrometric data and make it tidy
R
70
star
88

rb3

A bunch of downloaders and parsers for data delivered from B3
R
69
star
89

robotstxt

robots.txt file parsing and checking for R
R
68
star
90

codemetar

an R package for generating and working with codemeta
R
66
star
91

tradestatistics

R package to access Open Trade Statistics API
R
65
star
92

unconf17

Website for 2017 rOpenSci Unconf
JavaScript
64
star
93

roadoi

Use Unpaywall with R
R
64
star
94

terrainr

Get DEMs and orthoimagery from the USGS National Map, georeference your images and merge rasters, and visualize with Unity 3D
R
64
star
95

tiler

Generate geographic and non-geographic map tiles from R
R
64
star
96

comtradr

Functions for Interacting with the UN Comtrade API
R
64
star
97

NLMR

πŸ“¦ R package to simulate neutral landscape models πŸ”
R
63
star
98

parzer

Parse geographic coordinates
R
63
star
99

rWBclimate

R interface for the World Bank climate data
R
62
star
100

stats19

R package for working with open road traffic casualty data from Great Britain
R
61
star