Google 地图 API 动态 lat/lng 初始中心未显示正确位置

Google map API dynamic lat/lng initial center not showing correct location

我正在使用本地存储来存储 lat/lng,它是来自另一个组件的产品的一部分。我得到项目 lat/lng 并将它们设置为状态,以便在地图中使用。当我遍历所有内容时,它是正确的 lat:32.735962/lng:-96.275256,位于德克萨斯州达拉斯郊外的某个位置,但当地图呈现时,它位于几内亚湾的中心。如果我硬编码相同的 lat/lng 它会呈现正确的位置。

import { Map, GoogleApiWrapper, Marker } from 'google-maps-react';
import '../css/googleMaps.css';




export class Maps extends React.Component {
  constructor(props){
    super(props);
    this.state = {
        lat: '',
        lng: ''
    };
}


  componentDidMount(){
    const lat = localStorage.getItem('lat')
    const lng = localStorage.getItem('lng')
    this.setState({
      lat: lat,
      lng: lng
    })
  }

    logOut = () => {
        localStorage.removeItem('token');
        window.location = '/';
    };

    back = () => {
        localStorage.removeItem('lat')
        localStorage.removeItem('lng')
        window.location = '/patronmain';
    };

    render() {
      const mapStyles = {
        width: "60%",
        height: "60%",
      };
      return (
          <div>
                
                    <p className="lOut" onClick={() => this.logOut()}>Logout</p>
                    <p className="lOut" onClick={() => this.back()}>Back</p>
         
                <Map
                google={this.props.google}
                zoom={5}
                style={mapStyles}
                initialCenter={{lat: this.state.lat, lng: this.state.lng}}
                >
                   <Marker 
                    label='Made Here'
                    postion={{ lat: this.state.lat, lng: this.state.lng }} 
                    />
                </Map>
        </div>
      );
    }
  }



  export default GoogleApiWrapper({
    apiKey: ''
  })(Maps);

您的地图正以几内亚湾某处为中心,因为您的 initialCenter 值来自您所在的州,该州的值为“”。这意味着您的 latLng 的值为 "","",地图将其视为 0,0

请注意,initialCenter 参数采用包含纬度和经度坐标的对象。在加载时设置地图中心。

要在更改状态值时更改地图的中心,您需要使用 center 参数,该参数采用包含纬度和经度坐标的对象。如果您想在初始渲染后重新渲染地图,可以使用此选项。