React-leaflet v3.1.0 中的搜索框实现

IT技术 javascript reactjs leaflet react-leaflet
2021-05-10 07:36:06

我正在尝试searchbox在我的 React 应用程序中实现一个功能。但是在新版本的react-leaflet中收到此错误“尝试导入错误:'MapControl'未从'react-leaflet'导出”

import { MapContainer, TileLayer, Polygon, Marker, Popup } from 'react-leaflet';
import "./index.css";

// Cordinates of Marcillac
const center = [45.269169177925754, -0.5231516014256281]
const purpleOptions = { color: 'white' }

class MapWrapper extends React.Component {
    render() {
        return (
            <div id="mapid">
                <MapContainer center={center} zoom={13} scrollWheelZoom={true}>
                    <TileLayer
                        attribution='&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>'
                        url='https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png'
                    />
                </MapContainer>
            </div>
        )
    }
}

export default MapWrapper;

这里给出的实现https://stackoverflow.com/questions/48290555/react-leaflet-search-box-implementation并不像描述的那样工作MapControl

也尝试了第二种解决方案。

import { Map, useLeaflet } from 'react-leaflet'
import { OpenStreetMapProvider, GeoSearchControl } from 'leaflet-geosearch'

// make new leaflet element
const Search = (props) => {
    const { map } = useLeaflet() // access to leaflet map
    const { provider } = props

    useEffect(() => {
        const searchControl = new GeoSearchControl({
            provider,
        })

        map.addControl(searchControl) // this is how you add a control in vanilla leaflet
        return () => map.removeControl(searchControl)
    }, [props])

    return null // don't want anything to show up from this comp
}


export default function Map() {
  return (
    <Map {...otherProps}>
      {...otherChildren}
      <Search provider={new OpenStreetMapProvider()} />
    </Map>

  )
}

在这里我得到 map.addControl 未定义

1个回答

你的方法是正确的。您刚刚混淆了 react-leaflet 版本。

你这样做的方式在 react-leaflet 版本 2.x 中是正确的

对于 react-leaflet v.3.x,您的自定义组合应如下所示:

function LeafletgeoSearch() {
  const map = useMap(); //here use useMap hook

  useEffect(() => {
    const provider = new OpenStreetMapProvider();

    const searchControl = new GeoSearchControl({
      provider,
      marker: {
        icon
      }
    });

    map.addControl(searchControl);

    return () => map.removeControl(searchControl)
  }, []);

  return null;
}

您可以从useMaphook 而不是useLeaflet.

演示