0

Trying to get the [leafletLayers] option to work with ngx-leaflet.

I created a demo of this on Github, because Stackblitz is currently not loading leaflet correctly.

The demo works fine with the geo json data being added via the leaflet API after the mapReady call is made.

  private createGeoJsonLayer(map: L.Map): L.GeoJSON<any> {
    const layers: L.GeoJSON<any> = L.geoJSON(this.geoJsonData, {
      style: {
        weight: 2,
        color: 'orange',
        opacity: 0.8,
        fillColor: 'red',
        fillOpacity: 0.6,
      },
      onEachFeature: (feature, layer) => {
        this.onEachFeature(feature, layer);
      },
    });
    //==============================
    // Add layers to map
    //==============================
    layers.addTo(map);

    return layers;
  }

However layers.addTo(map) is commented out, the geo json layer no longer renders.

I was expecting it to render anyways since it is assigned in the template like this:

<div
leaflet
style="height: 300px;"
leaflet
[leafletLayers]="geoJsonLayers"
[leafletOptions]="leafletOptions"
(leafletMapReady)="mapReady($event)"
></div>

Thoughts?

Ole
  • 41,793
  • 59
  • 191
  • 359

1 Answers1

0

OK - Figured it out. The result of the call to L.geoJSON has to be wrapped in an array. So instead of returning L.geoJSON we have to return [L.geoJSON].

Here's a sample implementation:

  private createGeoJsonLayer(): [L.GeoJSON<any>] {
    const layers: L.GeoJSON<any> = L.geoJSON(this.geoJsonData, {
      style: {
        weight: 2,
        color: 'orange',
        opacity: 0.8,
        fillColor: 'red',
        fillOpacity: 0.6,
      },
      onEachFeature: (feature, layer) => {
        this.onEachFeature(feature, layer);
      },
    });
    return [layers];
  }

Note that the resetHightlight method needs access to the result, so the implementation should access the first item in array like this:

  private resetHighlight(featureLayer:any) {
    if (featureLayer) {
      this.geoJsonLayers[0].resetStyle(featureLayer);
    }
  }
Ole
  • 41,793
  • 59
  • 191
  • 359