Alireza
Alireza

Reputation: 171

How can I create one marker by react-native-maps?

We can create multi markers by DefaultMarkers, But I need just one marker. I need to delete before marker and create new marker. How can I do that?

I think other examples are not closer than this to my idea, So let me know if you have better idea.

let id = 0;


  constructor(props){
    super(props);
    this.state={
      markers: [],
    }
  }


onMapPress(e) {
    this.setState({
      markers: [
        ...this.state.markers,
        {
          coordinate: e.nativeEvent.coordinate,
          key: id++,
        },
      ],
    });
  }


  <MapView
     style={styles.map}
     initialRegion={{
        latitude: 28.95761453,
        longitude: 50.83710976,
        latitudeDelta: 0.0200,
        longitudeDelta: 0.0200,
     }}
     provider={this.props.provider}
     onPress={(e) => this.onMapPress(e)}>

              {this.state.markers.map(marker => (
                <Marker
                  key={marker.key}
                  coordinate={marker.coordinate}
                />
              ))}

   </MapView>

Upvotes: 0

Views: 282

Answers (1)

Patel Dhara
Patel Dhara

Reputation: 886

Just remove ...this.state.markers a line from the onMapPress method and check the output. Let me know if there is any error.

onMapPress(e) {
    this.setState({
      markers: [ 
        {
          coordinate: e.nativeEvent.coordinate,
          key: id++,
        },
      ],
    });
  }

Upvotes: 1

Related Questions