Question

When I try to add more than one polygon to a leaflet map with rCharts using the map$geoJson() function, only the last polygon appears on the map. The other ones are not displayed. Any idea on what I can do to add more than one polygon to my map? Below you can see a detailed description of what I did:

1. I am querying a postgis DB to get my polygons and as a result I get the code of a single polygon as a GeoJSON that looks approximately like this:

"{\"type\":\"Polygon\",\"coordinates\":[[[16.644953973395001,48.142664957703971], ...[16.644439684506018,48.143173899704649],[16.644953973395001,48.142664957703971]]]}"  

In sum I have 81 polygons and I want to display them on a leaflet map. I am using the rCharts package for this purpose.

2. As a next step I convert them with the package RJSONIO using the fromJSON function. Then the code of a single polygons looks approximately like this:

    $type
[1] "Polygon"

$coordinates
$coordinates[[1]]
$coordinates[[1]][[1]]
[1] 16.66885 48.42283

$coordinates[[1]][[2]]
[1] 16.66196 48.42634

$coordinates[[1]][[3]]
[1] 16.65877 48.42876

.
.
.

$coordinates[[1]][[62]]
[1] 16.67115 48.42179

$coordinates[[1]][[63]]
[1] 16.66885 48.42283

3. As the last step I create a leaflet map and add the polygons with the map$geoJson function:

map <- Leaflet$new()
map$tileLayer(provider = 'Stamen.TonerLite')

map$setView(c(48.42283, 16.66885), zoom = 10)
map$enablePopover(TRUE)
map$geoJson(polygon1)
map$geoJson(polygon2)
map$geoJson(polygon3)
map$geoJson(polygon4)
map$fullScreen(TRUE)
map$set(width = 800, height = 600)
map

With this method, only the last polygon (polygon4) is being display on the map, the other ones dont show up. Any suggestions on how to make them appear?

Was it helpful?

Solution

You have to construct a single geoJSON object with all your polygons in and add that. See here:

https://github.com/ramnathv/rCharts/blob/master/inst/libraries/leaflet/examples/example10.R

Note the json is a FeatureCollection with geometry-type Polygon features. Build that string from your polygon coordinates and add.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top