由于未定义的 getCurrentPosition,反应本机地理定位不起作用
react native geolocation does not work because of undefined getCurrentPosition
尝试检索用户的位置时,显示错误:'Cannot read property getCurrentPosition' of undefined。
import React, {Component} from 'react'
import {View, Text, StyleSheet, Image, ScrollView, SafeAreaView} from 'react-native';
import Topnavbar from './TopNavbar'
class googleMapsImages extends Component {
constructor(props){
super(props)
this.state = {
ready: false,
where: {lat: null, lng: null},
error: null
}
}
componentDidMount(){
let geoOptions = {
enableHighAccuracy: true,
timeOut: 20000,
maximumAge: 60 * 60 * 24
}
this.setState({
ready: false,
error: null
});
navigator.geolocation.getCurrentPosition(
this.geoSucces,
this.geoFailure,
geoOptions)
}
geoSucces = (position) => {
this.setState({ready: true})
}
geoFailure = (err) => {
this.setState({error: err.message})
}
文档说它不需要导入,所以我看不出我遗漏了什么?
npm install geolocation from react-native-community 然后执行
navigator.geolocation = require('@react-native-community/geolocation');
默认情况下,地理定位在 react native >=0.60
的版本中不可用
我通过以下方式修改了我的用法以解决该问题
import Geolocation from '@react-native-community/geolocation'
Geolocation.getCurrentPosition(handleSuccess, handleError, geoReqOptions)
尝试检索用户的位置时,显示错误:'Cannot read property getCurrentPosition' of undefined。
import React, {Component} from 'react'
import {View, Text, StyleSheet, Image, ScrollView, SafeAreaView} from 'react-native';
import Topnavbar from './TopNavbar'
class googleMapsImages extends Component {
constructor(props){
super(props)
this.state = {
ready: false,
where: {lat: null, lng: null},
error: null
}
}
componentDidMount(){
let geoOptions = {
enableHighAccuracy: true,
timeOut: 20000,
maximumAge: 60 * 60 * 24
}
this.setState({
ready: false,
error: null
});
navigator.geolocation.getCurrentPosition(
this.geoSucces,
this.geoFailure,
geoOptions)
}
geoSucces = (position) => {
this.setState({ready: true})
}
geoFailure = (err) => {
this.setState({error: err.message})
}
文档说它不需要导入,所以我看不出我遗漏了什么?
npm install geolocation from react-native-community 然后执行 navigator.geolocation = require('@react-native-community/geolocation'); 默认情况下,地理定位在 react native >=0.60
的版本中不可用我通过以下方式修改了我的用法以解决该问题
import Geolocation from '@react-native-community/geolocation'
Geolocation.getCurrentPosition(handleSuccess, handleError, geoReqOptions)