如何在 Googlemap api 函数 (initialcenter) 上传递 setState 的值?

How can I pass the value of setState on Googlemap api function (initialcenter)?

我正在尝试跟踪用户的位置。在这里我放了一个按钮 onclick 我试图在 google 地图上显示用户的位置。 我面临的问题是 initialCenter,我需要从 getCoordinates(position) 函数传递 setState 值。

我想在此 lat & lng 中传递 setstate 值。 有人吗??

import React, { Component } from 'react';
import '../User_Map/user_map.css'
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';

 

class User_Map extends Component {
    constructor(props) {
        super(props);
        this.state = {
            latitude: null,
            longitude: null,
            userAddress: null,
            zoom: 11
        }

        this.getLocation = this.getLocation.bind(this);
        this.getCoordinates = this.getCoordinates.bind(this);
        // this.reverseGeocodeCoordinates = this.reverseGeocodeCoordinates.bind(this);
    }
    
    getLocation(){
        
        if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(this.getCoordinates);
        }
        else{
            alert('Geolocation is not supported by this browser')
        }
    }

    getCoordinates(position){
        this.setState({
            latitude: position.coords.latitude,
            longitude: position.coords.longitude
        })

        
      //  this.reverseGeocodeCoordinates();
        // console.log(position)
    }

    // reverseGeocodeCoordinates(){
    //   fetch('https://maps.googleapis.com/maps/api/geocode/json?latlng=${this.state.latitude},${this.state.longitude}&sensor=false&key=AIzaSyDQ-XFSYZtSnkxUa678OjDbvlTPQr5xpFc')
    //   .then(response => response.json())
    //   // .then(data => this.setState({
    //   //   userAddress: data.results[0].formatted_address
    //   // }))
    //   .then(data => console.log(data))
    //   .catch(error => alert(error))
    // }

    handleLocationError(error){
      switch(error.code){
        case error.PERMISSION_DENIED:
          alert("User denied the request for Geolocation.")
          break;
          case error.POSITION_UNAVAILABLE:
            alert("Location information is unavailable.")
            break;
            case error.TIMEOUT:
              alert("The request to get user location timed out.")
              break;
              case error.UNKNOWN_ERROR:
                alert("An unknown error occured.")
                break;
                default:
                  alert("An unknown error occured.")
      }
    }
    
 
  render() {
    return (
     <>
      <div>
        <button onClick={this.getLocation}>Find Me</button> 
        <h4>HTML 5 Coordinates</h4>
        <p>Latitude: {this.state.latitude}</p>
        <p>Longitude: {this.state.longitude}</p>

        <Map google={this.props.google} 
        zoom={14}
        initialCenter={{
          lat: this.state.latitude,
          lng: this.state.longitude
        }}
        >
 
        <Marker onClick={this.onMarkerClick}
                name={'Current location'} />

        {/* <InfoWindow onClose={this.onInfoWindowClose}>
            <div>
              <h1>{this.state.selectedPlace.name}</h1>
            </div>
        </InfoWindow> */}
        </Map>


        {/* <h4>Google Maps Reverse Geocoding</h4>
        <p>Address: {this.state.userAddress}</p>
        {
          this.state.latitude && this.state.longitude ?
          <img src={'https://maps.googleapis.com/maps/api/staticmap?center=${this.state.latitude},${this.state.longitude}&zoom=14&size=400x300&sensor=false&markers=color:red%7C${this.state.latitude},${this.state.longitude}&key=AIzaSyDQ-XFSYZtSnkxUa678OjDbvlTPQr5xpFc'} alt=''/>
          :
          null
        } */}
      </div>
  
    </>
    );
  }
}

// export default User_Map;

export default GoogleApiWrapper({
    apiKey: ("YOUR API KEY")
  })(User_Map)

我看到您正在使用 google-maps-react library。请注意,这个库有多个可选属性,例如 initialCentercenterinitialCenter 接受一个包含纬度和经度坐标的对象。在加载时设置地图中心,而 center 获取包含纬度和经度坐标的对象。如果您想在初始渲染后重新渲染地图,请使用此选项。

因此,如果您想在从您的地理位置获取坐标后更改地图的中心,您可以将您的州坐标传递给 center 属性 而不是 initialCenter。请参阅下面的代码片段:

  <Map google={this.props.google} 
        zoom={14}
        initialCenter={{
          lat: this.state.latitude,
          lng: this.state.longitude
        }}
        center={{
          lat: this.state.latitude,
          lng: this.state.longitude
        }}
        >

我遇到的问题是在功能上,所以对我来说下面的代码工作正常。

<Map google={this.props.google} 
        zoom={14}
        initialCenter={{
          lat: this.state.latitude,
          lng: this.state.longitude
        }}
        center={{
          lat: this.state.latitude,
          lng: this.state.longitude
        }}
        >