I am trying to display a map with R using the rCharts
package. I am starting simple and so I want to add a polygon to my map. But I have no clue how. Any ideas? addPolygon
doesnt work.
map <- Leaflet$new()
map$tileLayer(provider = 'Stamen.TonerLite')
map$setView(c(48.1, 16.7), zoom = 10)
map$addPolygon(
c(48.99831, 49.08815, 49.08815, 48.99831, 48.99831),
c(13.42666, 13.42666, 13.56383, 13.56358, 13.42666),
layerId=c("1"),
options=opts,
defaultOptions=opts)
map
Add the polygon to your map by converting to geoJSON format, as in example 10 in the rCharts source code: https://github.com/ramnathv/rCharts/blob/master/inst/libraries/leaflet/examples/example10.R
Note how lat and long are different between the xy coords in the geoJSON and the setView. This here code gives me a blue box in the Czech Republic close to Germany.
xy = cbind(
c(13.42666, 13.42666, 13.56383, 13.56358, 13.42666),
c(48.99831, 49.08815, 49.08815, 48.99831, 48.99831)
)
xyjson = RJSONIO::toJSON(xy)
jsonX = paste(
'{"type":"FeatureCollection","features":[
{"type":"Feature",
"properties":{"region_id":1, "region_name":"My Region"},
"geometry":{"type":"Polygon","coordinates": [ ',xyjson,' ]}}
]
}')
polys = RJSONIO::fromJSON(jsonX)
map = Leaflet$new()
map$tileLayer(provider = 'Stamen.TonerLite')
map$setView(c(49.1,13.5), zoom = 8)
map$geoJson(polys)
map
# or print(map) from a script probably.
If you have more than one polygon, you need to create several structures of the {"type": "Feature",
and comma-separate them within the square brackets of the "features"
of the "FeatureCollection"
. I've re-indented things a bit to show the structure better. Its getting to the point where a templating system like the brew
package is going to help you...