首页 > 解决方案 > esri-leaflet-geosearch:如何将其与 React 集成

问题描述

在以下链接中,有在线演示案例展示了如何使用 esri-leaflet-geosearch 插件, 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));
    }
});

这个在线演示很好地支持地理搜索功能。

在我的 React 应用程序中,我还计划添加诸如传单的搜索框。但无法弄清楚如何做到这一点。

由于esri-leaflet-geosearch依赖esri-leaflet,所以安装了两个 npm 包,但找不到下一步。所以有什么帮助吗?

标签: javascriptreactjsleafletreact-leafletesri-leaflet

解决方案


您可以使用 react-leaflet 来实现。

首先安装传单、react-leaflet 和 esri-leaflet-geocoder 库。

之后将它们导入 index.js

然后在你的比赛中:

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>
    );
}

演示


推荐阅读