如何基于Javascript中的数值对动态列表项进行排序

问题描述 投票:0回答:2

这让我感到压力!

正在构建一个列出许多办公地点的应用。

应用程序将选择用户的位置并计算出他与所有办公室之间的距离。

现在,我需要根据列表与用户的距离以升序对它们进行排序。

现在,当由javascript加载应用程序时,li项目将在ul中动态创建。

我的应用程序连接并从Firebase中获取各个办公室的数据。

但是,距离是在客户端创建的,我需要根据该距离对列表项(办公室)进行排序。

最近的位置

<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.2.0/firebase-app.js"></script>

<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.2.0/firebase-firestore.js"></script>

<div class="container">
    <div class="section">

        <div class="row">
            <div class="all-parishes">
                <ul id="all-parishes" style="padding: 0; list-style: none; ">

                </ul>
            </div>

        </div>

    </div>
    <br>
    <br>
</div>
<script>
    //Distance Calculation
    // Your web app's Firebase configuration
    var firebaseConfig = {
        apiKey: "AIzaSyDXtwlWjWygp_sGx9R1qk-4gDuH9ZEx9xg",
        authDomain: "parish-connect.firebaseapp.com",
        databaseURL: "https://parish-connect.firebaseio.com",
        projectId: "parish-connect",
        storageBucket: "parish-connect.appspot.com",
        messagingSenderId: "304974921983",
        appId: "1:304974921983:web:9ac09b834259488951ccca",
        measurementId: "G-QWLPQ52Z7S"
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);

    var db = firebase.firestore();

    var lat1, lon1;

    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.watchPosition(showPosition);
        } else {
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }

    getLocation();

    function showPosition(position) {
        lat1 = position.coords.latitude;
        lon1 = position.coords.longitude;
        console.log(lat1);
        console.log(lon1);

        // To do: The code below creates a dynamic list items (<li>) and prints to the
        // <ul> container. I want to be able to sort the lists in ascending/descending order based on
        //the distances <p class="distance">${calcDistance(doc.data().lat, doc.data().lng).toFixed(5)} km away</p>
        var text = "";
        db.collection("parish-ghana").onSnapshot(querySnapshot => {
            querySnapshot.forEach(doc => {
                text += `
        <li>
        <div class="card demo-card-header-pic">
            <div style="background-image:url(${doc.data().pic_url})" valign="bottom" class="card-header"></div>
            <div class="card-content card-content-padding">
            <p class="parish-item">${doc.data().name}</p>
            <p class="distance">${calcDistance(doc.data().lat, doc.data().lng).toFixed(5)} km away</p>
            </div>
        </div>
        </li>
        <hr>
        `
            });

            document.getElementById("all-parishes").innerHTML = text;

        });
    }
    //End to do


    //When the location throws an error
    function onLocationError(e) {
        alert(e.message);
    }

    //Function to calculate distances
    function calcDistance(lat2, lon2) {

        function toRad(x) {
            return x * Math.PI / 180;
        }

        var R = 6371; // km 
        var dLat = toRad(lat2 - lat1);
        var dLon = toRad(lon2 - lon1);
        var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
            Math.sin(dLon / 2) * Math.sin(dLon / 2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        var d = R * c;
        return d;
    }
</script>

javascript html firebase
2个回答
0
投票

尝试下面的小提琴中使用的方法。

https://jsfiddle.net/techtichemant/dh6nu7m0/4/

  <ul> 
            <li><div>   apple</div></li> 
                        <li><div>   pinapple</div></li>
                        <li><div>   mango   </div></li> 
            <li><div>   banana</div></li>
        </ul> 
        <br> 

        <center> 
            <button> 
                click here 
            </button> 
        </center> 

        <p id = "triger_elem" style =  
            "text-align:center; color:green; font-size:20px; font-weight:bold;"> 
        </p> 

function Ascending_sort(a, b) { 
                return ($(b).find('div').text().toUpperCase()) <  
                    ($(a).find('div').text().toUpperCase()) ? 1 : -1;  
            } 
            $('button').on('click', function() { 
                $("ul li").sort(Ascending_sort).appendTo('ul'); 
                $("#triger_elem").text("sorted"); 
            });     

您的问题的小示范


0
投票

您可以先将querySnapshot映射到数据对象的简单数组,然后将distance作为附加属性添加到每个对象。然后通过该新属性对该数组进行排序。最后,按照您已有的方式执行循环(对动态表达式稍作更改)。我还将在循环中使用.map(),然后将.join HTML片段与<hr>一起使用。

这是它的外观:

db.collection("parish-ghana").onSnapshot(querySnapshot => {
    document.getElementById("all-parishes").innerHTML = querySnapshot.docs
    .map(doc => doc.data())
    .map(data => ({
        ...data,
        distance: calcDistance(data.lat, data.lng)
    }))
    .sort((a, b) => a.distance - b.distance)
    .map(data => `
    <li>
        <div class="card demo-card-header-pic">
            <div style="background-image:url(${data.pic_url})" valign="bottom" class="card-header"><\/div>
            <div class="card-content card-content-padding">
                <p class="parish-item">${data.name}<\/p>
                <p class="distance">${data.distance.toFixed(5)} km away<\/p>
            <\/div>
        <\/div>
    <\/li>
    `)
    .join('<hr>\n');
});
© www.soinside.com 2019 - 2024. All rights reserved.