简体   繁体   中英

Show marker to Google Map on Click

I'm using the Google map react package to integrate google map in my react project. I could render the map markers with the lat, long that i have in my json array. 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 = ({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. Use one more state variable isClick , update that value on click of map, and render the marker conditionally.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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