0

我有一个 Reactjs 应用程序,我在其中使用 google-map-react 库生成地图。我在从通过浏览器获得的地理位置集中地图时遇到问题。加载页面时,地图的中心位置与我的位置不同。

我有以下代码:

state = {
        lat: 40,
        long: 80,
        zoom: 10,
    }

componentDidMount() {    
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(this.showPosition, this.posError);
        } else {
            alert("Sorry, Geolocation is not supported by this browser.");
        }
    }
posError = () => {
        if (navigator.permissions) {
            navigator.permissions.query({ name: 'geolocation' }).then(res => {
                if (res.state === 'denied') {
                    alert('Enable location permissions for this website in your browser settings.')
                }
            })
        } else {
            alert('Unable to access your location. You can continue by submitting location manually.')
        }
    }
    showPosition = async (position) => {
        let lat = position.coords.latitude
        let long = position.coords.longitude
        //console.log(lat);
        //console.log(long);
        this.setState({ lat: lat });
        this.setState({ long: long });
    }

render() {
        const {
            lat,
            long,
            zoom,
        } = this.state;

        return (
            <>

                <div className="row">
                    <div className="col-xl-12 col-md-6 mb-4">
                        <div style={{ height: '600px' }}>
                            <GoogleMapReact
                                bootstrapURLKeys={{ key: 'API_KEY' }}
                                defaultCenter={{ lat: lat, lng: long }}
                                defaultZoom={zoom}
                            >
                            </GoogleMapReact>
                        </div>
                    </div>
                </div>
            </>
      )
  }

纬度和经度数据被正确接收,但是我上面提到的问题正在发生。我尝试在navigator.geolocation.getCurrentPosition的await方法中使用async(componentDidMount),但没有成功。

4

0 回答 0