import React,{Component } from 'react';
import {
withGoogleMap,
GoogleMap,
withScriptjs,
Marker,
InfoWindow,
} from 'react-google-maps';
import {compose, withProps, withStateHandlers} from 'recompose';
import places from 'places.json';
class MapComponent extends Component {
constructor (props) {
super (props);
this.state = {
zoom: 11,
center: {lat: 29.969516, lng: -90.103866},
markers: [],
lat:'',
lng:'',
markersLoaded: false,
};
}
componentDidMount () {
let geocoder = new window.google.maps.Geocoder ();
geocoder.geocode ({address: 'Bakerstreet, 2'}, function (results, status) {
if (status == 'OK') {
this.setState ({
lat: results[0].geometry.location.lat (),
lng: results[0].geometry.location.lng (),
});
} else {
console.log (
'Geocode was not successful for the following reason:',
status
);
}
});
}
render () {
const { lat, lng } = this.state;
const GoogleMapExample = withGoogleMap (props => (
<GoogleMap
defaultZoom={props.zoom}
defaultCenter={props.center}
options={{styles: props.mapdynamic ? darkThemeStyle : lightThemeStyle}}
>
{props.places &&
props.places.map ((place, i) => {
let lat = parseFloat (place.latitude, 10);
let lng = parseFloat (place.longitude, 10);
return (
<Marker
id={place.id}
key={place.id}
position={{lat: lat, lng: lng}}
icon="http://maps.google.com/mapfiles/ms/icons/blue-dot.png"
onMouseOver={props.onToggleOpen.bind (this, i)}
>
{props.infoWindows[i].isOpen &&
<InfoWindow onCloseClick={props.onToggleOpen.bind (i)}>
<div>{place.name}</div>
</InfoWindow>}
</Marker>
);
})}
</GoogleMap>
));
return (
<div>
<GoogleMapExample
center={{lat: 40.6451594, lng: -74.0850826}}
zoom={10}
places={places} />
</div>
);
}
}
export default compose (
withProps ({
googleMapURL: 'https://maps.googleapis.com/maps/api/js?key=YOUR KEY&libraries=geometry,drawing,places',
loadingElement: <div style={{height: `100%`}} />,
containerElement: (
<div style={{height: '100%', width: '100%', padding: '10px'}} />
),
mapElement: <div style={{height: '100%'}} />,
}),
withStateHandlers (
props => ({
infoWindows: props.places.map (p => {
return {isOpen: false};
}),
}),
{
onToggleOpen: ({infoWindows}) => selectedIndex => ({
infoWindows: infoWindows.map ((iw, i) => {
iw.isOpen = selectedIndex === i;
return iw;
}),
}),
}
),
withScriptjs,
withGoogleMap
) (MapComponent);
我在这里是通过使用反应订单组件编写谷歌地图组件来实现的。但是当我试图运行它时,我遇到了某种错误。
你可以看看它,让我知道这里有什么问题。我收到以下错误,例如 Invariant Violation: Required props containerElement or mapElement is missing。您需要同时提供它们。该
google.maps.Map
实例将在 mapElement 上初始化,并由 containerElement 包装。您需要同时提供它们,因为 Google 地图要求 DOM 在初始化时具有高度。
问候