noob112233
noob112233

Reputation: 15

react native mapboxgl - mapping data to PointAnnotation onSelected problem

I am dynamically adding PointAnnotation components to my MapView. The points are added correctly coordinate wise, however none of them retain their onSelected callback EXCEPT the last one added to the map. Here is the map function. . .

const markers = points.map((data, index) => { // points is an array of objects containing coordinates and names
    return (
        <MapboxGL.PointAnnotation
            key={index}
            coordinate={data["coords"]}
            onSelected={() => alert(data["name"])}
        />
    )
})

The points are located correctly on the map with the provided coordinates, so the data being mapped is okay. I don't understand though why the onSelected only fires on the very last added point.

Any idea as to why that is happening??

Upvotes: 0

Views: 973

Answers (1)

Anthony
Anthony

Reputation: 106

First : you should add an unique id to <MapboxGL.PointAnnotation />

If annotations haven't an id the results of your event will be overwritten on each index.

That's why you got only the last

or:

the onSelect props take a payload. you can try something like :

const markers = points.map((data, index) => { // points is an array of objects containing coordinates and names
    return (
        <MapboxGL.PointAnnotation
            key={index}
            id={`annotation_${data.name}_${index}`}
            coordinate={data["coords"]}
            onSelected={(payload) => console.log(payload);}
        />
    )
})

You will see what you got and use the payload to find data.

Hope it will help.

Upvotes: 2

Related Questions