javascript - 如何在我想基于它创建的自定义库中使用传单中提供的 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
我正在尝试扩展传单,但出了点问题。有人可以看看,让我知道如何使它工作。
一些链接:
任何帮助,将不胜感激。非常感谢您提前!!
解决方案
我不明白你为什么把事情搞得这么复杂。
我建议创建一个普通函数而不是扩展一个类。
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);
}
推荐阅读
- mysql - 动态内容类型:一张有很多列的表格还是每个表格一张?
- angularjs - 如何根据下拉值在表上应用过滤器
- excel - 如何将列中的每个唯一名称复制到主表?
- java - 如何实现连接服务类以在我们的拨号器应用程序中添加运营商呼叫功能?
- node.js - 使用 pm2 和 bytenode 启动 NodeJS 应用程序
- java - Java 8:ArrayDeque<>.poll 在并行环境中返回 null
- docker - 使用 Gitlab CI 将 Docker 镜像部署到 Heroku
- python - ModuleNotFoundError:没有名为“numpy”的模块;但是安装了numpy
- python - test 和 django 之间的不一致::int() 参数必须是字符串,但 TypeError:字符串索引必须是整数
- contiki - 如何使用 contiki 的 serial-perl 工具将 mote 的输出与时间戳一起写入文件?