首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用google-maps-react npm打包--有没有一种方法可以单击地图来添加标记?

使用google-maps-react npm打包--有没有一种方法可以单击地图来添加标记?
EN

Stack Overflow用户
提问于 2018-03-02 06:13:12
回答 1查看 273关注 0票数 2

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

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

它不是一个可用的功能吗?有人能给我指个方向吗?

谢谢。

我的代码:

代码语言:javascript
复制
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>
    );
  }
}
EN

回答 1

Stack Overflow用户

发布于 2018-11-20 09:22:13

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

代码语言:javascript
复制
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”都会发生变化。但是你可以直接修改代码来创建一个新的Marker。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49059524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档