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

标签 javascript leaflet

我想向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/

相关文章:

openstreetmap - 多个制造商在同一个地方与传单

javascript - ng-bind-html 不能正常工作

leaflet - 如何使传单中的 map 边界响应式?

javascript - 如何防止传单弹出窗口中的表单出现 "submit"事件

javascript - 访问对象数组中的值

popup - 如何在单击传单群集组上显示弹出窗口

leaflet - 悬停时绑定(bind)工具提示并永久保留在传单中

javascript - 如何通过获取获取添加到 Backbone 集合的项目的索引?

javascript - 这个简短的 Javascript 有什么问题?

javascript - useState 和 props 的变化