geojson格式篩選及處理的解決方案

漏刻有時 發表於 2020-11-28

獲取geojson檔案

 //獲取geojson檔案;
    $.getJSON('zj.json', function (data) {
        var d = [];
        for (var i = 0; i < data.features.length; i++) {
            //篩選條件;
            var str = data.features[i].properties.FULLNAMEPI;
            if (str.search("haishuqu") != -1) {
                d.push({
                    type: "Feature",
                    geometry: {"type": "Polygon", coordinates: data.features[i].geometry.coordinates},
                    properties: {
                        country: "海曙區",
                        name: data.features[i].properties.FULLNAMEPI.replace("zhejiangshengningboshihaishuqu", "")
                    }
                })
            }
        }

        //轉為字串
        var json = JSON.stringify(d);
        var begin = '{"type": "FeatureCollection", "features": ';
        var end = '}';
        //拼接標準格式字串;
        //console.log(begin + json + end);
        var txt = begin + json + end;

        //匯出檔案;
        exportRaw('text.json', txt)
    });

匯出檔案的封裝函式

    //匯出txt檔案;
    function fakeClick(obj) {
        var ev = document.createEvent("MouseEvents");
        ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        obj.dispatchEvent(ev);
    }

    function exportRaw(name, data) {
        var urlObject = window.URL || window.webkitURL || window;
        var export_blob = new Blob([data]);
        var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
        save_link.href = urlObject.createObjectURL(export_blob);
        save_link.download = name;
        fakeClick(save_link);
    }

獲取字串長度

    //獲取字串長度;
    function getLength(str) {
        console.log(str.length);
    }

Done!

相關文章