javascriptangularleafletesri-leaflet

How to add search control on leaflet map using Angular 2?


I am using leaflet.js with ngx-leaflet and esri-leaflet-geocoder packages.

I am able to using search box on the leaflet map with plain JavaScript. All I need is the following line:

var searchControl = L.esri.Geocoding.geosearch().addTo(mymap);

But I am unable to accomplish this in Angular. I tried the following:

layers = [];
searchControl = Geocoding.geosearch();
this.layers.push(this.searchControl); // in the constructor

HTML:

<div style="height: 300px;"
     leaflet
     [leafletOptions]="options"
     [leafletLayersControl]="layersControl"
     [leafletLayers]="layers"
     [leafletFitBounds]="this.polygon.getBounds()"
     (leafletClick)="mapClicked($event)">
</div>

I am getting the error which says:

ERROR Error: "The provided object is not a Layer."

I consoled searchControl and the result is same for both plain JavaScript and Angular.


Solution

  • A workaround not sure if it's a best solution.

    Import CSS of the plugin:

    import 'style-loader!esri-leaflet-geocoder/dist/esri-leaflet-geocoder.css';
    

    Pass the map object when the map is ready:

    <div style="height: 300px;"
         leaflet
         [leafletOptions]="options"
         [leafletLayersControl]="layersControl"
         [leafletLayers]="layers"
         [leafletFitBounds]="polygon.getBounds()"
         (leafletClick)="mapClicked($event)"
         (leafletMapReady)="onMapReady($event)">>
    </div>
    

    And add controller to the map same like plain JavaScript:

    onMapReady(map: L.Map) {
      setTimeout(() => {
        map.invalidateSize(true);
        this.searchControl.addTo(map);
      }, 0);
    }