react-google-maps icon indicating copy to clipboard operation
react-google-maps copied to clipboard

Removing Markers Without Click

Open reeceaw opened this issue 10 years ago • 3 comments

Hi there,

I am using react-google-maps with a GPS tracker to keep track of where a boat is. At the moment I am just placing markers and then removing and placing a new one when I need to update the position.

Is there a way to change the lat and lon of a current marker defined in state and show it on the map, or do I have to delete and recreate a marker? If I do need to recreate markers, how can I delete one? I tried using the script from the example (on the handleMarkerRightclick) but I am struggling to use it outside of the handleMarkerRightclick.

Ideally I'd like to have a marker with the same name to reference it by - like 'taxi1' - So I can delete taxi1 then create taxi1.

Thanks.

reeceaw avatar Oct 06 '16 15:10 reeceaw

Here the bit of code I have been trying (and failing with). screen shot 2016-10-06 at 16 20 50

reeceaw avatar Oct 06 '16 15:10 reeceaw

@reeceaw you just need to call setState once:

componentDidMount() {
  const socket = io('localhost:3000');
  socket.on('receiveCoord', function(givenCoords) {
    console.log('Coordinates received clientside: LAT: ' + givenCoords.lat + ', LON: ' + givenCoords.lon);
    //REMOVE LAST MARKER
    const targetMarker = taxi1;
    const lastNewMarkers = this.state.markers.filter(marker => marker !== targetMarker);
    //ADD NEW MARKER
    const nextMarkers = [
      ...lastNewMarkers,
      {
        position: { lat: givenCoords.lat, lng: givenCoords.lon },
        defaultAnimation: 2,
        key: Date.now(), // Add a key property for: http://fb.me/react-warning-keys
      },
    ];
    this.setState({
      markers: nextMarkers,
    });
    console.log('SET STATE!');
  }.bind(this));
}

Please ask on StackOverflow instead in the future. This is not related to react-google-maps but only react.

tomchentw avatar Oct 07 '16 03:10 tomchentw

Thanks for the help @tomchentw

reeceaw avatar Oct 07 '16 09:10 reeceaw