Nidhi Patel
Nidhi Patel

Reputation: 1292

Remove marker from google map in react native

Is possible to remove marker from map view? How to remove marker from google map view. I using "react-native-maps" display google map.

Please Help.

Upvotes: 7

Views: 6365

Answers (2)

clauziere
clauziere

Reputation: 1342

Here's how I do it. Essentially, you need to keep an array of markers in the state, then remove the marker you want to delete from the state.

I store the list of markers in the state like so:

this.state = {
  markers: [],
};

When you actually create the markers, you pass the index in the function that will remove the marker from the state. In this case onMarkerPress(index)

  createMarkers() {
    return this.state.markers.map((marker, index) => (
      <Marker
        draggable
        onPress={event => this.onMarkerPress(index)}
        key={index}
        coordinate={{
          latitude: parseFloat(marker.latitude),
          longitude: parseFloat(marker.longitude),
        }}
      />
    ));
  }

Here's the onMarkerPress function:

  onMarkerPress(index) {
    this.state.markers.splice(index, 1);
    this.setState({markers: this.state.markers});
  }

And finally, you map component will look like this:

<MapView
          style={styles.map}
          mapType={'satellite'}
          provider={PROVIDER_GOOGLE}
          initialRegion={{
            latitude: 45.50235905860018,
            longitude: -73.60357092645054,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          }}
          onLongPress={e => this.addNewMarker(e)}>
          {this.createMarkers()}
        </MapView>

And that's it!

Upvotes: 0

Mahdi Bashirpour
Mahdi Bashirpour

Reputation: 18803

To be able to remove or add markers, you just need to do this

//Note : my map markers is => this.props.markers

componentDidMount() {
    this.renderMarkers(this.props.markers)
}


async renderMarkers(mapMarkers) {
    let markers = [];
    markers = mapMarkers.map(marker => (<Marker
            key={marker.code}
            coordinate={{latitude: marker.lat, longitude: marker.lng}}
            onPress={{}}
        />)
    );
    this.setState({markers});
}


refreshMarkers() {
    this.renderMarkers(this.props.markers).then(() => {
        this.forceUpdate();
    });
}


render() {
    return (
        <MapView
            ref={(ref) => this.mapView = ref}
            style={styles.map}
            region={this.props.coordinate}
        >
            {this.state.markers}
        </MapView>
    );
}

Upvotes: 1

Related Questions