3

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?

kboul
  • 13,836
  • 5
  • 42
  • 53
Chris Bao
  • 2,418
  • 8
  • 35
  • 62

1 Answers1

6

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

kboul
  • 13,836
  • 5
  • 42
  • 53
  • 1
    Works great! One additional thingI had to use an explicit call in the constructor to first create the ref: this.mapRef = React.createRef(); For anybody else new to React refs like me.... – Bonkles Apr 06 '20 at 14:20