简体   繁体   English

在点击时向Google地图显示标记

[英]Show marker to Google Map on Click

I'm using the Google map react package to integrate google map in my react project. 我正在使用Google Map React软件包将Google Map集成到我的React项目中。 I could render the map markers with the lat, long that i have in my json array. 我可以使用json数组中的经纬度来绘制地图标记。 But on clicking the map the marker to show the clicked area is not displaying but i'm getting the lat, lng values with _onClick function 但是在点击地图时,显示点击区域的标记未显示,但是我通过_onClick函数获取经纬度值

_onClick = ({x, y, lat, lng, event}) => {
    this.setState({
        lat: lat, lng: lng
    }); 
}
<GoogleMapReact onClick={this._onClick}
    center={this.state.center}
    defaultZoom={this.props.zoom} 
    options = {{ mapTypeId: 'satellite' }}
    style={{height: '680px', width: '560px'}}
>
    {this.state.markers.map((marker, i) =>{
          return(
                 <AnyReactComponent key={i}
                      lat={marker.lat}
                      lng={marker.lng}
                      img_src={marker.img_src}
                  />

                )
    })}      
</GoogleMapReact>

How can i solve this to display the marker on the clicked area? 我该如何解决才能在点击区域显示标记?

You are storing the lat,lng for the clicked area, so you need to render the marker for those values. 您将存储单击区域的lat,lng因此需要渲染这些值的标记。 Use one more state variable isClick , update that value on click of map, and render the marker conditionally. 再使用一个状态变量isClick ,在单击地图时更新该值,并有条件地渲染标记。

Like this: 像这样:

_onClick = ({x, y, lat, lng, event}) => {
    this.setState({
        lat: lat, 
        lng: lng,
        isClicked: true
    }); 
}

<GoogleMapReact onClick={this._onClick}
    center={this.state.center}
    defaultZoom={this.props.zoom} 
    options = {{ mapTypeId: 'satellite' }}
    style={{height: '680px', width: '560px'}}
>
    {this.state.markers.map((marker, i) => {
        return(
            <AnyReactComponent key={i}
                lat={marker.lat}
                lng={marker.lng}
                img_src={marker.img_src}
            />

        )
    })} 
    {this.state.isClicked? 
        <AnyReactComponent key={i}
            lat={this.state.lat}
            lng={this.state.lng}
            img_src={marker.img_src}
        /> 
    :null}   
</GoogleMapReact>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM