1

I'm trying to push array of markers after clicking on map. I've tried this (under "this doesn't work") but it raise an error.

PS: how can I get location of my cursor to create new marker depending on cursor position?

I'm really stuck. Thanks for any advice.

import React, { Component } from 'react';
import { withGoogleMap, GoogleMap, Marker } from 'react-google-maps';

class Map extends Component {
  state = {
    markers: [
      {position: {lat:49.79, lng: 18}, key:1},
      {position: {lat:49.69, lng: 18}, key:2},
      //{position: {lat:49.59, lng: 18}, key:3}
    ]
  };

//this doesn't work

  handleMapClick() {

    this.setState({ markers: [...this.state.markers, {position: {lat:49.59, 
    lng: 18}, key:3}]})
  }



   render() {
       const GoogleMapExample = withGoogleMap(props => (
       <GoogleMap
          defaultCenter = { { lat: 49.82, lng: 18.16 } }
          defaultZoom = { 10 } 
          onClick = {this.handleMapClick}
       >

          {this.state.markers.map(marker => <Marker position= 
          {marker.position} key={marker.key} />)}
       </GoogleMap>
   ));
   return(
      <div>
        <GoogleMapExample
        containerElement={ <div style={{ height: `600px`, width: 
        '800px',display: "inline-block" }} /> }
        mapElement={ <div style={{ height: `100%` }} /> }



       />
       </div>
       );}};

 export default Map;
Martin
  • 11
  • 1
  • You likely did not preserve the `this` context in your callback (so it doesn't refer to your component instance). `console.log(this)` to verify this. You should `.bind(this)` where you pass the callback. – Tobias K. Aug 28 '18 at 17:01

3 Answers3

0

Bind you your callback function or use arrow function

binding

onClick = {this.handleMapClick.bind(this)}

arrow function

onClick = {(arg) => this.handleMapClick(arg) }

From the doc:

You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

This is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if you refer to a method without () after it, such as onClick={this.handleClick}, you should bind that method.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
0

Transform your handleMapClick into an arrow function or bind it in constructor (these are equivalent solutions)

handleMapClick = () => {

    this.setState({ markers: [...this.state.markers, {position: {lat:49.59, 
    lng: 18}, key:3}]})
  }
Vladislav Sorokin
  • 369
  • 1
  • 2
  • 14
0

Create constructor to bind this to functions.

constructor(props){
  super(props);
  this.handleMapClick = this.handleMapClick.bind(this)
}
Amruth
  • 5,792
  • 2
  • 28
  • 41