0

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?

maRtin
  • 6,336
  • 11
  • 43
  • 66

1 Answers1

1

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.

Spacedman
  • 92,590
  • 12
  • 140
  • 224
  • 1
    This is the recommended approach. I believe LeafletJS allows one to add simple geometries one at a time, but I have not exposed that in the rCharts binding. So `geoJSON` is the way to go. – Ramnath May 10 '14 at 20:11
  • Multiple geoJSON layers in rCharts would be handy, but eventually one has to bite the bullet and realise one may as well write the JS oneself. – Spacedman May 11 '14 at 07:42
  • That is True. There has to be a balance. – Ramnath May 11 '14 at 15:39
  • And how is it possible to write a geoJson from multiple datasets, and displaying points and polygons on it? – aruizga Feb 12 '15 at 21:38