Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I drop a pin at location on React Native MapView press?

Tags:

react-native

https://facebook.github.io/react-native/docs/mapview.html

I am looking for an example on how to press on the map to create an annotation that location.

I know how to add the annotation, but do not know how to get the coordinates of where I just pressed.

like image 839
atkayla Avatar asked Oct 16 '25 22:10

atkayla


2 Answers

I can't see anything about an onPress event in the react-native MapView docs or code - But found this on github: https://github.com/lelandrichardson/react-native-maps - looks pretty good and has an onPress event which returns the coordinates (https://github.com/lelandrichardson/react-native-maps#mapview-events)

Hope this helps!

like image 139
David Avatar answered Oct 19 '25 13:10

David


I use the onPress method on the MapView like this:

class DefaultMarkers extends React.Component {

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

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

     render() {
         return (
            <View style={styles.container}>
                <MapView
                   style={styles.map}
                   onPress={e => this.onMapPress(e)}
                >
                   {this.state.markers.map(marker => (
                       <Marker
                          key={marker.key}
                          coordinate={marker.coordinate}
                       />
                   ))}
                </MapView>
            </View>
        );
    }
}

Check out the full example full example on the react-native-maps github

like image 28
Dustin Spengler Avatar answered Oct 19 '25 12:10

Dustin Spengler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!