gpt4 book ai didi

javascript - Leaflet - 如何向类添加静态函数?

转载 作者:行者123 更新时间:2023-11-27 23:34:30 25 4
gpt4 key购买 nike

我想向L.GeoJSON添加一个函数称为“getLatLngPath”,它将采用 geojson 对象并为 geojson 中的任何 LineString 或多线字符串功能发出单个经纬度数组。简单的。

因为我没有重写任何代码,而且它是一个静态函数,所以我的想法是使用 include()方法,希望我可以访问 L.GeoJSON.getLatLngPath(...) 的函数。代码:

L.GeoJSON.include({
/*
* Returns a single array containing all the latlngs from each LineString feature
*/
getLatLngPath: function(geojson, reverse) {
reverse = typeof reverse === undefined ? false : reverse;
var path = [];
if (geojson.type === 'FeatureCollection') {
for(var i=0; i < geojson.features.length; i++) {
// Recursively call this function on each feature
path = path.concat(this.getLatLngPath(geojson.features[i]));
}
} else if (geojson.type === 'Feature' && (geojson.geometry.type === 'LineString' || geojson.geometry.type === 'MultiLineString')) {
return L.GeoJSON.coordsToLatLngs( // function existing in L.GeoJSON
geojson.geometry.coordinates,
geojson.geometry.type === 'LineString' ? 0 : 1, // Need one more level deep if a MultiLineString
reverse);
}
return this._pruneDuplicates(path);
},

/*
* Prunes duplicate-adjacent latlngs
*/
_pruneDuplicates: function (path) {
var i=1;
while (i < path.length){
if (path[i-1][0] == path[i][0] && path[i-1][1] == path[i][1]) {
path.splice(i, 1);
} else {
i++;
}
}
return path;
}
});

(注意,代码尚未测试,与此问题无关。)

调用 L.GeoJSON.getLatLngPath(...) 不起作用——它说它不是一个函数。但是,如果我调用工厂方法(它只返回它的"new"实例),它就会起作用:

L.geoJson().getLatLngPath(...);

我无意狡辩,但这很丑陋。我不需要为静态方法创建新对象如何使我的函数成为直接从 L.GeoJSON 调用的静态方法?

最佳答案

该方法在类原型(prototype)上可用:

L.GeoJSON.prototype.getLatLngPath(...);

关于javascript - Leaflet - 如何向类添加静态函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34232531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com