esri-leaflet-geosearch: how to integrate it with React

4.2k views Asked by At

In the following link, there is online demo case showing how to user esri-leaflet-geosearch plugin, https://codepen.io/exomark/pen/dafBD

var searchControl = new L.esri.Controls.Geosearch().addTo(map);

var results = new L.LayerGroup().addTo(map);

searchControl.on('results', function(data){
    results.clearLayers();
    for (var i = data.results.length - 1; i >= 0; i--) {
      results.addLayer(L.marker(data.results[i].latlng));
    }
});

This online demo works well to support the geosearch function.

And in my React app, I plan to add such as search box for leaflet as well. But can't figure out how to do this.

As esri-leaflet-geosearch depends on esri-leaflet, so installed both npm packages, but can't find next step. so any help?

1

There are 1 answers

1
kboul On BEST ANSWER

You can achieve that using react-leaflet.

First install leaflet, react-leaflet & esri-leaflet-geocoder libraries.

After that import them in index.js

Then in your comp:

import React, { Component, createRef } from 'react';
import L from 'leaflet';
import * as ELG from 'esri-leaflet-geocoder';
import { Map, TileLayer } from 'react-leaflet';
...
componentDidMount() {
    const map = this.mapRef.current.leafletElement;
    const searchControl = new ELG.Geosearch().addTo(map);
    const results = new L.LayerGroup().addTo(map);

    searchControl.on('results', function(data){
        results.clearLayers();
        for (let i = data.results.length - 1; i >= 0; i--) {
            results.addLayer(L.marker(data.results[i].latlng));
        }
    });
}

render() {
    const center = [37.7833, -122.4167]
    return (
        <Map 
            style={{height: '800px'}}
            center={center} 
            zoom="10"
            ref={this.mapRef}>
            <TileLayer
                attribution="&amp;copy Google"
                url={'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'} />
            <div className='pointer'></div>
        </Map>
    );
}

Demo