im 尝试使用 Google 地图 react 库初始化谷歌地图 并希望每次我根据纬度和经度状态搜索位置时地图都会更改。但是,我收到一个错误,说提供给谷歌地图的道具中心无效。出于某种原因,当我放入一个数字而不是这个.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;
地图.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>
)
}
}
你不应该用引号来包装你的latitude
和longitude
。当您用引号包装它们时''
它将纬度、经度类型number
转换为string
.所以你的纬度、经度属性应该声明像
latitude: 37.774929,
longitude: -122.419416
而不是
latitude: '37.774929',
longitude: '-122.419416'
所以你的状态应该遵循
this.state = {
zoom: 13,
maptype: 'roadmap',
place_formatted: '',
place_id: '',
place_location: '',
address: '',
latitude: 37.774929,
longitude: -122.419416
};