How To Add Marker On Map By Click Using React-google-maps?
I'm struggling to find a very simple example of how to add a marker(s) to a Google Map when a user left clicks on the map using React-google-maps in components based. Need help. co
Solution 1:
This is a generic example that demonstrates how to display marker on map click:
constMap = compose(
withStateHandlers(() => ({
isMarkerShown: false,
markerPosition: null
}), {
onMapClick: ({ isMarkerShown }) =>(e) => ({
markerPosition: e.latLng,
isMarkerShown:true
})
}),
withScriptjs,
withGoogleMap
)
(props =><GoogleMapdefaultZoom={8}defaultCenter={{lat:-34.397, lng:150.644 }}
onClick={props.onMapClick}
>
{props.isMarkerShown && <Markerposition={props.markerPosition} />}
</GoogleMap>
)
exportdefaultclassMapContainerextendsReact.Component {
constructor(props) {
super(props)
}
render() {
return (
<divstyle={{height: '100%' }}><MapgoogleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg&v=3.exp&libraries=geometry,drawing,places"loadingElement={<divstyle={{height: `100%` }} />}
containerElement={<divstyle={{height: `400px` }} />}
mapElement={<divstyle={{height: `100%` }} />}
/>
</div>
)
}
}
Solution 2:
Check this code with the edited version which add the marker
constInitialMap = withGoogleMap(props => {
var index = this.marker.index || [];
return(
<GoogleMapref={props.onMapLoad}zoom={13}center={{lat:21.178574, lng:72.814149 }}
onClick={props.onMapClick}
>
{props.markers.map(marker => (
<Marker
{...marker}
onRightClick={() => props.onMarkerRightClick(marker)}
/>
))}
</GoogleMap>
)
});
exportdefaultclassMapContainerextendsComponent{
constructor(props){
this.state = {
markers:[{
position:{
lat: 255.0112183,
lng:121.52067570000001,
}
}]
}
}
render(){
return(
<divstyle={{height:"100%"}}><InitialMapcontainerElement={
<divstyle={{height:"150px"}}/>
}
mapElement={
<divstyle={{height:"150px"}} />
}
markers={this.state.markers} />
</div>
)
}
}
Post a Comment for "How To Add Marker On Map By Click Using React-google-maps?"