Michael Cheng
Michael Cheng

Reputation: 10451

How do I get the key or coordinates of a Marker in react-native-maps in onPress?

I'm using react-native-maps to render a MapView with several Markers. I want to perform some actions and animations when a user clicks on a marker. For that, I am binding a function (e.g., onMarkerPress) to each Marker's onPress. The problem I'm running into is that I cannot figure out how to find out which marker is triggering the function. Is there any way to get a reference to the marker/identifying key prop? Even the coordinates would do as I can use those to lookup the marker.

Upvotes: 3

Views: 8449

Answers (1)

Florin Dobre
Florin Dobre

Reputation: 10232

I found 2 ways to do that. Most probably the first one is the best choice:

1. pass the info you need about the marker as a second argument to the bind of _onMarkerPress as below:

render() {

    return (
        <View>
            <Text>MySupaFancyMap</Text>
            <MapView
                style={styles.map}
                region={this.state.region}
                onRegionChangeComplete={this._onRegionChangeComplete.bind(this)}
            >
                <MapView.Marker
                    coordinate={this.state.marker.latlng}
                    title={this.state.marker.title}
                    description={this.state.marker.description}
                    onPress={this._onMarkerPress.bind(this, this.state.marker)}
                />
            </MapView>
        </View>
    );
}
_onMarkerPress (markerData) {
    alert(JSON.stringify(markerData));
}

In my case this.state.marker is an object like this:

       {
            latlng: {
                latitude: REGION.latitude,
                longitude: REGION.longitude
            },
            title:'MyHouse',
            weather: '26 Celsius'

        }

2. extract the info you need from the event info like this:

 <MapView>
//codes here
onPress={this._onMarkerPress.bind(this)}
>
 
<MapView.Marker
       coordinate={this.state.marker.latlng}         
/>
<MapView>

and with:

_onMarkerPress (mkr) {
    console.warn(mkr.nativeEvent.coordinate);
}

I would definitely go with the first solution. More details about Markers here: https://github.com/airbnb/react-native-maps/blob/master/docs/marker.md

Note: as a best practice it is recommended that you don't have binds at render. Better solutions are to add them in the constructor like this:

constructor (props) {
  super(props);
  this._onMarkerPress = this._onMarkerPress.bind(this);
}

or use the arrow function. When I wrote the answer I didn't know about this.

Upvotes: 5

Related Questions