smeijer / leaflet-geosearch

A geocoding/address-lookup library supporting various api providers.
https://smeijer.github.io/leaflet-geosearch/
MIT License
1.03k stars 273 forks source link

How to handle events in react ? #166

Closed dirodriguezm closed 6 years ago

dirodriguezm commented 6 years ago

This is how I create the control:

export default class SearchBar extends MapControl{
  constructor(props){
    super(props);
  }
  createLeafletElement() {
    return GeoSearchControl({
      provider: new OpenStreetMapProvider(),
      style:'bar',
      autoComplete: true,
      autoClose:true,
      autoCompleteDelay: 100,
      retainZoomLevel: false,
      searchLabel: 'Ingrese localidad',
      keepResult: true,
      showMarker: true,
      maxMarkers: 1,
      animateZoom: true,
      marker: {                                           // optional: L.Marker    - default L.Icon.Default
        icon: new L.Icon.Default(),
        draggable: false,
      },

    });
  }

}

and this is how I add it to the map:

<Map
          center={position}
          zoom={this.state.zoom}
          style={style}
          onDblclick={this.mapClicked}
          onLocationfound={this.handleLocationFound}
          onGeosearchShowlocation={this.handleLocationFound}
          ref="map"
          doubleClickZoom={false}
        >
          <TileLayer
            attribution="&amp;copy <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />

          {this.state.markers.map((position) =>
            <Marker key={position} position={position}>
              <Popup>
                <span>
                  {this.state.comuna ? this.state.comuna.nombre : ""}
                </span>
              </Popup>
            </Marker>
          )}
          <SearchBar />
        </Map>

onLocationfound is not working here, please help.

dirodriguezm commented 6 years ago

Okay, I found a way to fix it.

When using leaflet with react, events are called onEventname (on with lowercase and the first letter of event name with uppercase). The problem is that the default event is called "geosearch/showlocation" but you cant call onGeosearch/showlocation, so the fix is to modify the event name on leafletControl.js and change "geosearch/showlocation" to something like "showlocation" and then, on your map component you can do something like:

<Map 
    onShowlocation={this.handleLocationFound}
>
<SearchBar/>
</Map>