提供给“GoogleMap”的道具“center”无效。React.js

ron*_*man 1 google-maps reactjs

我试图使用谷歌地图反应库初始化谷歌地图,并希望每次我根据纬度和经度状态搜索位置时地图都会改变。但是我收到一个错误,说提供给谷歌地图的道具中心无效。出于某种原因,当我放置一个数字而不是 this.state 时它会起作用......有人可以帮忙吗?

应用程序.js

 import React, { Component } from 'react';
    import axios from "axios";
    import './App.css';
    import PlacesAutocomplete from 'react-places-autocomplete'
    import { geocodeByAddress, geocodeByPlaceId, getLatLng } from 'react-places-autocomplete'
    import UserForm from "./components/UserForm.js";

    import Super from "./components/super.js";


    import MapContainer from './components/Map.js'
    import Map from './components/Map.js';
    import { classnames } from './components/helpers';

    const google = window.google;



    class App extends Component {
     constructor() {
        super();
        this.state = {
          zoom: 13,
          maptype: 'roadmap',
          place_formatted: '',
          place_id: '',
          place_location: '',
          address: '',
          latitude: '37.774929',
          longitude: '-122.419416'

        };
      }

    <div>
    <Map center= {{lat: this.state.latitude, lng: this.state.longitude}}
          />
              <div>

        );
      }
    };

export default App;
Run Code Online (Sandbox Code Playgroud)

地图.js

import React, { Component } from 'react'
import GoogleMapReact from 'google-map-react'
import marker from './marker.png'

import {geolocated} from 'react-geolocated';
const AnyReactComponent = ({ text }) => <div><img src={marker} style={{height:'50px',width:'50px'}}/></div>;
export default class Map extends Component {

  static defaultProps = {

    zoom: 11
  }
render() {
    return (
      <div className='google-map' style={{width: '100%',height: '400px',backgroundColor: 'grey'}}>
        <GoogleMapReact
          center={ this.props.center }
          defaultZoom={ this.props.zoom }>
          <AnyReactComponent
            lat={ this.props.center.lat}
            lng={ this.props.center.lng }
            text={ '' }
          />

        </GoogleMapReact>

      </div>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

web*_*san 5

你不应该用引号包裹你的latitudelongitude 。当你用引号包裹它们时,'' 它会将纬度、经度类型转换numberstring. 所以你的纬度,经度属性应该声明为

latitude: 37.774929,
longitude: -122.419416
Run Code Online (Sandbox Code Playgroud)

代替

    latitude: '37.774929',
    longitude: '-122.419416'
Run Code Online (Sandbox Code Playgroud)

所以你的状态应该遵循

        this.state = {
          zoom: 13,
          maptype: 'roadmap',
          place_formatted: '',
          place_id: '',
          place_location: '',
          address: '',
          latitude: 37.774929,
          longitude: -122.419416

        };
Run Code Online (Sandbox Code Playgroud)