使用google-maps-react npm打包 - 有没有办法点击地图添加标记



我正在使用google-maps-react组件,但我似乎找不到有关如何通过单击地图动态添加标记的任何信息。 https://github.com/fullstackreact/google-maps-react

我可以用代码很好地添加一个标记,但我希望用户能够通过单击来添加它,并且看不到如何添加该事件侦听器。我已经有一个用于显示标记信息的事件侦听器。

这不是可用的功能吗?有人可以指出我正确的方向吗?

谢谢。

我的代码:

export class MapContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showingInfoWindow: false,
      activeMarker: {},
      selectedPlace: {}
    };
    // binding this to event-handler functions
    this.onMarkerClick = this.onMarkerClick.bind(this);
    this.onMapClicked = this.onMapClicked.bind(this);
  }
  onMarkerClick = (props, marker, e) => {
    this.setState({
      selectedPlace: props,
      activeMarker: marker,
      showingInfoWindow: true
    });
  };
  onMapClicked = props => {
    if (this.state.showingInfoWindow) {
      this.setState({
        showingInfoWindow: false,
        activeMarker: null
      });
    }
  };
  render() {
    return (
      <div>
        <Map google={this.props.google} onClick={this.onMapClicked} style={{width: '70%', height: '80%', position: 'relative'}} className={'map'} zoom={2}>
          <Marker onClick={this.onMarkerClick} name={"Current location"} />
          <Marker
          onClick={this.onMarkerClick}
          title={'The marker`s title will appear as a tooltip.'}
          name={'SOMA'}
          position={{lat: 37.778519, lng: -122.405640}} />
          <InfoWindow
            marker={this.state.activeMarker}
            visible={this.state.showingInfoWindow}
          >
            <div>
              <h1>{this.state.selectedPlace.name}</h1>
            </div>
          </InfoWindow>
        </Map>
        </div>
    );
  }
}

您可以使用以下代码通过单击地图来放置标记。

mapClicked = (a, b, c) => {
if (this.state.showingInfoWindow) {
  this.setState({
    showingInfoWindow: false,
    activeMarker: null
  });
} else {
  let lat = c.latLng.lat();
  let lng = c.latLng.lng();
  let houseLocation = { lat: lat, lng: lng };
  this.setState({ houseLocation });
}

mapClicked接受三个参数,第三个"c"是地图上的坐标。因此,您可以获取这些坐标并在这些位置制作标记。此代码只允许您放置一个标记,每次单击地图时,"houseLocation"都会发生变化。但是您可以更改代码以创建新的标记。

最新更新