簡體   English   中英

如何在我要基於它創建的自定義庫中使用 leaflet 中提供的 distanceTo 方法?

[英]How can I use the distanceTo method provided in leaflet in my custom library that I want to create based on it?

我在我的項目中使用 leaflet。 現在有這個distanceTo方法,它基本上計算兩個坐標之間的距離。 現在我想創建單獨的 JS 文件,它將有一個名為 getDistance() 的 function,我想保留單獨計算坐標之間距離的邏輯。 這是代碼

文件 a.js

function getDistance() {
var getDistanceCal = (L.Layer ? L.Layer : L.Class).extend({
    calculateDistance: function (latA, latB) {
        if (latA !== undefined && latB !== undefined) {
            
            //How can I make it run distanceTo method here where leaflet Js is being called in another file 
            let dis = latA.distanceTo(latB);
            let distanceConversion = ((dis) / 1000).toFixed(0);
            let distanceKm = distanceConversion;
            return distanceKm || 0;
        }
        else {
            return 0;
        }
    }

});

L.markerDistance = function () {
    return new getDistanceCal();
};

return L;}

在我調用 leaflet.js 的另一個文件中,我調用它:

文件 b.js

CALLING THE FUNCTION
markerDistanceFunction().markerDistance().calculateDistance(1.3521, 103.81) // should give distance but throws an error that distanceTo is not defined

我正在嘗試延長 leaflet 但出了點問題。 有人可以看看,讓我知道如何讓它工作。

一些鏈接:

分機 leaflet

距離到

任何幫助,將不勝感激。 非常感謝您!

我不明白你為什么把事情搞得這么復雜。

我建議創建一個普通的 function 而不是擴展 class。

function calculateDistance(latA, latB) {
        if (latA !== undefined && latB !== undefined) {
            
            //How can I make it run distanceTo method here where leaflet Js is being called in another file 
            let dis = latA.distanceTo(latB);
            let distanceConversion = ((dis) / 1000).toFixed(0);
            let distanceKm = distanceConversion;
            return distanceKm || 0;
        }
        else {
            return 0;
        }
    }


distance = calculateDistance(latlng, latlng);

但要回答您的問題,問題是distanceTo僅適用於L.LatLng class 而不適用於普通數字。

markerDistanceFunction().markerDistance().calculateDistance(L.latLng(1.3521, 103.81),latlngFromMarker)

當你想覆蓋默認distanceTo function src時:

L.LatLng.prototype.distanceTo = function (other) {
    return (L.CRS.Earth.distance(this, L.latLng(other)) / 1000).toFixed(0);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM