I am not finding a way to sort my array based on the shortest to farthest distance from the IP of the user who is accessing the webApp.
I have a component for the items, (the cards)
ListingItem.svelte:
<script>
import { onMount } from 'svelte'
export let listing
export let id
let position = null
onMount(() => {
navigator.geolocation.getCurrentPosition((pos) => {
position = pos
})
})
$: distance = position ? getDistance(position) : 0
function getDistance(pos) {
var lat = position.coords.latitude
var lng = position.coords.longitude
var latlng1 = {
lat: lat,
lng: lng
}
var latlng2 = {
lat: listing.geolocation.lat,
lng: listing.geolocation.lng
}
// calculate the distance between latlng1 and latlng2
return getDistanceFromLatLngInKm(latlng1, latlng2)
}
function getDistanceFromLatLngInKm(latlng1, latlng2) {
var R = 6371 // Radius of the earth in km
var dLat = deg2rad(latlng2.lat - latlng1.lat) // deg2rad below
var dLon = deg2rad(latlng2.lng - latlng1.lng)
var a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2rad(latlng1.lat)) *
Math.cos(deg2rad(latlng2.lat)) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2)
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
var d = R * c // Distance in km
return d
}
function deg2rad(deg) {
return deg * (Math.PI / 180)
}
</script>
<div>
<p>
{listing.name}
</p>
<p>
{listing.location}
</p>
<p>
{distance.toFixed(2)} km from you
// I get distance from the function above // it works nice
</p>
</div>
I use the component inside my index.svelte:
<script>
.... fetchListings from Firebase
const params = [
listingsRef,
where('type', '==', 'all'),
orderBy('timestamp', 'desc'),
limit(9)
] // order by descending
... other things ...
</script>
<div>
{#await fetchListings()}
{#if loading}
<div>
<StretchLoader/>
</div>
{:else if listings && listings.length > 0}
<ul>
{#each listings as listing (listing.id)}
<div class="grid-items">
<ListingItem listing={listing.data} id={listing.id} />
</div>
{/each}
</ul>
{/if}
{/await}
</div>
I pass the data that is inside Firebase via props to ListItem.svelte:
<ListingItem listing={listing.data} id={listing.id} />
I need an approach (help) to solve this problem. And sort the array based on the shortest to farthest distance from the IP of the user who is accessing the webApp.