#' Extract highways from Open Street Map data
#'
#' Uses the \code{osmar} package to fetch OSM data and extract only highway
#' nodes and ways.
#'
#' @param box A bounding box as generated by \code{prettymapr::searchbbox} or
#' \code{osmar::center_bbox}
#' @param apisource An OSM api source as generated by the \code{osmar::osmsource_*}
#' functions.
#'
#' @return An \code{osmar} object containing nodes and ways of highways.
#' @export
#'
#' @examples
#' wv <- prettymapr::searchbbox("wolfville, ns", source="google")
#' d2 <- osmdata_highways(wv)
#'
osmdata_highways <- function(box, apisource=osmar::osmsource_api()) {
if(class(box) == "matrix") {
box <- c(box[1], box[2], box[3], box[4])
names(box) <- c("left", "bottom", "right", "top")
class(box) <- "bbox"
}
osmdata <- osmar::get_osm(box, source=apisource)
hways_muc <- subset(osmdata, way_ids = osmar::find(osmdata, osmar::way(osmar::tags(k == "highway"))))
hways <- osmar::find(hways_muc, osmar::way(osmar::tags(k == "name")))
hways <- osmar::find_down(osmdata, osmar::way(hways))
hways_muc <- subset(osmdata, ids = hways)
#data.frame(hways_muc$nodes$attrs) to get lat/lons as data frame
return(hways_muc)
}
#' Get the nearest OSM nodes to a point
#'
#' Finds the nearest OSM node(s) to a lat/lon coordinate.
#'
#' @param osmarobj an \code{osmar} object
#' @param lon The longitude
#' @param lat The latitude
#' @param num The number of points to return
#'
#' @return a \code{list} containing the OSM data pertaining to the points as well
#' as the computed distances
#' @export
#'
#' @examples
#' #use extract_highways to get highway data
#' wv <- prettymapr::searchbbox("wolfville, ns", source="google")
#' d2 <- osmdata_highways(wv)
#'
#' #use nearest_nodes to get nearest road names to a location
#' nearesthwys <- osmdata_nearest_nodes(d2, -64.3557, 45.0857, num=10)
#' waysdata <- subset(d2, way_ids = nearesthwys$info$way_ids)
#' waynames <- unique(as.character(waysdata$ways$tags$v[waysdata$ways$tags$k=="name"]))
#'
osmdata_nearest_nodes <- function(osmarobj, lon, lat, num=1) {
ats <- osmarobj$nodes$attrs
ats$dists <- geodist(ats$lon, ats$lat, lon, lat)
ats <- ats[order(ats$dists,decreasing = FALSE),]
node_id <- ats$id[1:num]
dist <- ats$dists[1:num]
return(list(info=osmar::find_up(osmarobj, osmar::node(node_id)), dist=dist))
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.