KT-mongo
KT-mongo

Reputation: 2212

How to add coordinates to google-maps-react on a user click event?

I'm trying to add a marker on based on a user clicking on the map for the google-maps-react npm. Currently the code below will generate markers and add them to the this.state = { markers:[ ] } and I would like to map them out on the map component. However, the position:event.latLng, will not register the lat and lng and the marker will only be created and inserted into the state with the key: Date.now() and defaultAnimation: 2. Below the code:

import React, { Component } from 'react';
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';

export class MapContainer2 extends Component {
  constructor(props){
    super(props);

    this.state={
      lat:null,
      lng:null,
      markers:[]
    }
  }

  componentDidMount(){
    navigator.geolocation.getCurrentPosition(position=>
      this.setState({
        lat:position.coords.latitude,
        lng:position.coords.longitude,
      }));
   }

   mapClicked = (event) =>{
     const { markers } = this.state;
     this.setState({
       markers:[
         {
           position:event.latLng,
           key: Date.now(),
           defaultAnimation: 2,
         },
         ...markers
       ]

     })
   }

  render() {
    if (!this.props.loaded) {
      return <div>Loading...</div>
    }
    const style = {
    width: '100%',
    height: '100vh'
  }
    return (
      <Map
       google={this.props.google}
       zoom={11}
       style={style}
       initialCenter={{
          lat: this.state.lat,
          lng: this.state.lng
       }}
       center={{
          lat: this.state.lat,
          lng: this.state.lng
       }}
       onClick={this.mapClicked}
       >
       <Marker
         title={'Geolocation'}
         position={{
           lat:this.state.lat,
           lng:this.state.lng,
         }}
       />


      </Map>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: ('AIzaSyCZ7rgMN34kWkGvr8Pzkf_8nkT7W6gowBA')
})(MapContainer2)

Upvotes: 3

Views: 2163

Answers (1)

KT-mongo
KT-mongo

Reputation: 2212

I resolved it by updating the function mapClicked with the following:

mapClicked = (mapProps, map, event) => {
    const { markers } = this.state;
    const lat = event.latLng.lat();
    const lng = event.latLng.lng();
    let url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=myapikey`
    axios.get(url).then(response => {
        this.setState({
          googleReverseGeolocation:response.data.results[0].formatted_address,
          markers:[{position:{lat:event.latLng.lat(),lng:event.latLng.lng()}}, ...markers],
          latClick:lat,
          lngClick:lng
        });
       this.props.onMapClickChange(lat, lng, response.data.results[0].formatted_address);
    });
  }

Upvotes: 3

Related Questions