所以我对反应和传单真的很陌生,但我想做的基本上就是让用户输入一些输入,然后按回车键后,触发一个事件,然后该事件飞到从该输入生成的坐标。我正在使用地理编码,经纬度坐标已成功生成。但是我不知道如何使地图飞到那个位置。这是我到目前为止所拥有的:
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='© <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
prop,然后当您不想将其用于某个组件时,使用它飞到另一个位置MapContainer's
child.
this.state = {
position: [43.653225, -79.383186],
map: null
}
删除引用并使用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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)