I want to fetch top 5 markers that are closest to the users location (in order) and put that into a useState object. How can I achieve that?
My map screen loadflow:
- Load map
- Get user location (stored in location useState)
- HTTP Get request for markers location (each marker got lat and ltd)
- Fetch markers around user (if agreed to share location)
- Display screen
const fetchClosestRendelok = async () => {
//Get markers in an area here and add to a json
}
const fetchRendeloData = async () => {
const data = await fetchRendelok()
setRendelok(data)
}
useEffect(() => {
fetchRendeloData()
fetchClosestRendelok()
}, []);
return (
<View style={styles.container}>
<MapView style={styles.map}
provider={PROVIDER_GOOGLE}
region={mapRegion}
showsUserLocation={true}
onPress={() => setSelectedMarkerIndex("")}
>
{
rendelok.map((rendelok) => {
return (
<Marker
key={rendelok.id}
coordinate={{ latitude:parseFloat(rendelok.lat), longitude:parseFloat(rendelok.ltd) }}
onPress={() => markerClick(rendelok)}
tracksViewChanges={false}
>
<View>
<MaterialCommunityIcons name="hospital-marker" size={selectedMarkerIndex === rendelok.id ? 80 : 30} color={selectedMarkerIndex === rendelok.id ? 'red' : color_theme_light.iconColor}/>
</View>
</Marker >
)
})
}
</MapView>
</View>
);
}

In the end this was my solution, I used libary to order my markers by distance https://github.com/manuelbieh/geolib, then I just compared the coords with my original array.