我没有找到一种方法来根据与访问 webApp 的用户 IP 的最短到最远距离对数组进行排序。
我有一个项目组件(卡片)
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>
我在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>
我通过 props 将 Firebase 内部的数据传递给 ListItem.svelte:
<ListingItem listing={listing.data} id={listing.id} />
我需要一种方法(帮助)来解决这个问题。并根据与访问 webApp 的用户的 IP 的最短到最远距离对数组进行排序。
最佳答案
<script>
...
async function fetchAndSort() {
const listings = await fetchListings()
try {
const currentPosition = await getCurrentPosition()
const listingsWithDistance = listings.map(listing => {
listing.distance = getDistance(currentPosition, listing)
return listing
})
return listingsWithDistance.sort((l1, l2) => l1.distance - l2.distance)
}catch(e) {
// error while getting currentPosition > no need to sort
// either map distance to 0 or handle missing d. in ListingItem
return listings
}
}
function getCurrentPosition() {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject)
})
}
</script>
{#await fetchAndSort() then listings}
{#each listings as listing (listing.id)}
...
{/each}
{/await}
关于svelte - 从距 IP 最近到最远的距离对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73210419/