[英]Cannot read property 'lat' of undefined and undefined
I'm now trying to feed the position of the user through the variable (coords)
but every time I pass any variable into onClickUserLoc() the variable has the error我现在正在尝试通过变量
(coords)
输入用户的 position 但每次我将任何变量传递给 onClickUserLoc() 时,变量都会出现错误
Cannot read property 'lat' of undefined
无法读取未定义的属性“纬度”
and when I console.log it states undefined?当我 console.log 它状态未定义? The coords variable holds an array of location data such as lng and lat but become undefined in onClickUserLoc().
coords 变量包含一个位置数据数组,例如 lng 和 lat,但在 onClickUserLoc() 中未定义。
Code:代码:
export default class App extends React.Component {
constructor() {
super();
this.state = {
ready: false,
where: { lat: '', lng: '' },
error: null,
};
this.onClickUserLoc = this.onClickUserLoc.bind(this)
}
componentDidMount() {
let geoOptions = {
enableHighAccuracy: true,
timeOut: 20000,
maximumAge: 60 * 60 * 24,
};
this.setState({ ready: false, error: null });
navigator.geolocation.getCurrentPosition(
this.geoSuccess,
this.geoFailure,
geoOptions
);
}
mapRef = React.createRef();
geoSuccess = (position) => {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
console.log(this.state.where?.lng);
console.log(this.state.where?.lat);
this.setState({
ready: true,
where: { lat: position.coords.latitude, lng: position.coords.longitude
},
});
console.log(this.state.where?.lng);
console.log(this.state.where?.lat);
};
geoFailure = (err) => {
this.setState({ error: err.message });
console.log(this.state.error);
};
onClickUserLoc({ coords }) {
this.mapRef.current.leafletElement.flyTo(coords, 15);
console.log(coords);
}
render() {
const coords = [this.state.where?.lat, this.state.where?.lng];
return (
<>
<Button onPress={this.onClickUserLoc}>
<Map
center={[...]}
zoom={0}>
style={{ height: "90vh" }}
ref={this.mapRef}
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</map>
</>
)
}
If I understand correctly you want to fly to the position you are right now (geolocation).如果我理解正确,您想飞往 position,您现在就是(地理位置)。 Variable
coords
variable is defined inside render method.变量
coords
变量在 render 方法中定义。 You either pass the coords variable as an argument to button's onPress:您可以将 coords 变量作为参数传递给按钮的 onPress:
<Button onPress={() => this.onClickUserLoc(coords)}></Button>
but you don't need to destructure it here但你不需要在这里解构它
onClickUserLoc(coords) { // here no need to destructure it.
this.mapRef.current.leafletElement.flyTo(coords, 15);
}
or use the state variable where
directly inside onClickUserLoc
without passing any argument:或直接
where
onClickUserLoc
内部使用 state 变量而不传递任何参数:
onClickUserLoc() {
const {
where: { lat, lng }
} = this.state;
this.mapRef.current.leafletElement.flyTo([lat, lng], 15);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.