我似乎无法显示从json到google-maps-react的索引,我可以看到所有标记出的标记,但是它们显示的默认标记没有弹出窗口。这是放置<InfoWindow>
的代码,反应是抱怨我必须放置一个父div,当这样做时,我目前看不到任何标记。
我的car2go json映射正确,只是没有打印出name={content.name}
。
我的map.js组件:
import React, { Component } from "react";
import Car2go from "../data/car2go/vehicles.json";
import { Map, InfoWindow, Marker, GoogleApiWrapper } from "google-maps-react";
export class MapContainer extends Component {
constructor(props) {
super(props);
this.onMarkerClick = this.onMarkerClick.bind(this);
this.state = {
showingInfoWindow: false,
activeMarker: {},
selectedPlace: {},
name: null
};
}
onMarkerClick(props, marker, e) {
this.setState({
selectedPlace: props,
activeMarker: marker,
showingInfoWindow: true
});
}
render() {
const google = window.google;
const style = {
width: "70%",
height: "70%",
margin: "0 auto"
};
//const google = window.google;
return (
<Map
google={this.props.google}
style={style}
initialCenter={{
lat: 53.59301,
lng: 10.07526
}}
zoom={12}
onClick={this.onMapClicked}
>
{Car2go.placemarks.map((content, index) => {
return (
<div>
<Marker
title={index}
name={content.name}
position={{
lat: content.coordinates[1],
lng: content.coordinates[0]
}}
onClick={this.onMarkerClick}
name={content.name}
/>
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
>
<div>
<h1>{this.state.selectedPlace.name}</h1>
</div>
</InfoWindow>
</div>
);
})}
</Map>
);
}
}
export default GoogleApiWrapper({
apiKey: "xxxxx"
})(MapContainer);
答案 0 :(得分:1)
我猜想React抱怨的错误与此类似:
React无法识别DOM元素上的
mapCenter
道具
如果是,则此错误的根本原因与使用Marker
容器包装div
组件有关:
<div>
<Marker
...
/>
</div>
以及google-maps-react
Map
组成元素的方式呈现子元素。在这种情况下,Map
个道具将转移到div
个元素而不是Marker
个组件中。有关更多详细信息,请参见Unknown Prop Warning文章。
为避免此错误,可以考虑采用以下方法:
div
容器替换为React.Fragment
Marker
组件这里是一个例子:
class Map extends Component {
constructor() {
super();
this.state = {
map: null
};
this.handleMapReady = this.handleMapReady.bind(this);
}
handleMapReady(mapProps, map) {
this.setState({ map: map });
}
render() {
return (
<Map
google={this.props.google}
className={"map"}
initialCenter={this.props.center}
zoom={this.props.zoom}
onReady={this.handleMapReady}
>
{this.state.map &&
places.map((place, i) => {
const mapProps = Object.assign({}, this.props);
mapProps.map = this.state.map;
return (
<React.Fragment key={i}>
<Marker
{...mapProps}
onClick={this.handleMarkerClick}
position={place.position}
placeIndex={i}
name={place.name}
/>
</React.Fragment>
);
})}
</Map>
);
}
}
但是,除了上述更改之外,我将提出另一种方法,特别是创建InfoWindow
组件的单个实例并按如下所示进行管理:
<Map
google={this.props.google}
className={"map"}
initialCenter={this.props.center}
zoom={this.props.zoom}
>
{places.map((place, i) => {
return (
<Marker
key={i}
onClick={this.handleMarkerClick}
position={place.position}
placeIndex={i}
name={place.name}
/>
);
})}
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
onClose={this.handleClose}
>
<div>{this.state.selectedPlace.name}</div>
</InfoWindow>
</Map>