首页 > 解决方案 > 如何在我想基于它创建的自定义库中使用传单中提供的 distanceTo 方法?

问题描述

我在我的项目中使用传单。现在有这个distanceTo方法,它基本上计算两个坐标之间的距离。现在我想创建一个单独的 JS 文件,该文件将具有一个名为 getDistance() 的函数,并且我想保留分别计算坐标之间距离的逻辑。这是代码

文件 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

我正在尝试扩展传单,但出了点问题。有人可以看看,让我知道如何使它工作。

一些链接:

扩展传单

距离至

任何帮助,将不胜感激。非常感谢您提前!!

标签: javascripthtmljqueryleaflet

解决方案


我不明白你为什么把事情搞得这么复杂。

我建议创建一个普通函数而不是扩展一个类。

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班级而不适用于正常人数。

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

当你想覆盖默认distanceTo函数src时:

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


推荐阅读