Sorting The Items In The Flatlist
In my react native application, I am showing services that are offered by my office and the location of those services in a flatlist. I am also showing the miles of the service fr
Solution 1:
You could sort
the array by distance
before you give it as data to the FlatList
It would probably be a good idea to put the distance in the state, so that you don't have to do the calculations in both the sorting and in the _renderItem
method.
<FlatList
data={newList.sort((a, b) => {
const aDist = geodist(
{ lat: a.cLat, lon: a.cLong },
{ lat: a.LatL, lon: a.Long2 },
"mi"
);
const bDist = geodist(
{ lat: b.cLat, lon: b.cLong },
{ lat: b.LatL, lon: b.Long2 },
"mi"
);
return aDist - bDist;
})}
ItemSeparatorComponent={this.FlatListItemSeparator}
renderItem={this._renderItem}
keyExtractor={(item, index) => index}
/>
Solution 2:
Using the Tholle method, i used the Geolib Liberary. And using the method getDistance to compare distances this is the result.
<FlatList data={newList.sort((a, b) => {
const aDist = getDistance({ //get distance between plaza and current locationlatitude: a.latitud,
longitude: a.longitud
}, {
latitude: latitude,
longitude: longitude,
})
const bDist = getDistance({ //get distance between plaza and current locationlatitude: b.latitud,
longitude: b.longitud
}, {
latitude: latitude,
longitude: longitude,
})
return aDist - bDist; })} ItemSeparatorComponent={this.FlatListItemSeparator} renderItem={this._renderItem}keyExtractor={(item, index) => index} />
Where latitude and longitud are the user's lcoation and the object data has already a latitude and longitude. Dont forget to import:
import {getDistance} from'geolib';
Post a Comment for "Sorting The Items In The Flatlist"