如何飞到react-leaflet中的某个位置

How to fly to a location in react-leaflet

所以我对 React 和 leaflet 真的很陌生,但我想做的基本上就是让用户输入一些输入,在他们按下 enter 后,触发一个事件,然后飞到从该输入生成的坐标。我正在使用地理编码,并且经纬度坐标已成功生成。但是我不确定如何让地图飞到那个位置。这是我目前所拥有的:

import './App.css';
import * as React from "react";
import { ChakraProvider } from "@chakra-ui/react";
import { MapContainer, TileLayer, Marker, Popup, useMapEvents } from 'react-leaflet'
import 'leaflet/dist/leaflet.css'
import Geocode from "react-geocode";
import SearchBar from './SearchBar';

class App extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      position: [43.653225, -79.383186]
    }
  }
  mapRef = React.createRef();

  changePos (pos) {
    this.setState({position: pos});
    this.mapRef.current.flyTo(pos);
  }

  render () {
    return (
      <ChakraProvider resetCSS = {false}>
        <div className = "App">
          <div id="title">
            <h1>
              CovidStopSpots
            </h1>
              <p>A responsive tracker for Covid-19.</p>
          <SearchBar changePos = {this.changePos.bind(this)}></SearchBar>
          </div>
          <div id="map">
            <MapContainer center={this.state.position} zoom={13} scrollWheelZoom={false} ref={this.mapRef}>
              <TileLayer
                attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
              />
              <Marker position={[43.653225, -79.383186]}>
                <Popup>
                  A pretty CSS3 popup. <br /> Easily customizable.
                </Popup>
              </Marker>
            </MapContainer>
          </div>
      </div>
      </ChakraProvider>
    )
  }
}

export default App;

当前代码也产生了这个错误:

Unhandled Rejection (TypeError): Cannot read property 'flyTo' of null

在 react-leaflet 版本 3 中,您可以使用 whenCreated 道具获取地图实例,然后在您不想将其用于 [=] 的组件时使用它飞到另一个位置14=] child.

this.state = {
      position: [43.653225, -79.383186],
      map: null
 }

移除 ref 并使用 whenCreated prop

<MapContainer center={this.state.position} zoom={13} scrollWheelZoom={false} whenCreated={map => this.setState({ map })}>

然后在你的 changePos 事件中使用 this.state.map 飞行

 changePos (pos) {
    this.setState({position: pos});
    const {map} = this.state;
    if (map) map.flyTo(pos);
 }