[GIS] How to convert KMZ file to JSON

arcgis-javascript-apigoogle mapsjsonkmlkmz

I'm writing a ArcGIS JS project, in which user will upload KMZ which will be displayed on map, since ArcGIS doesn't have a magic trick to do it, I want to convert KMZ to JSON (or KML) and then display that JSON.

I've already tried https://github.com/sntran/kmz-geojson , but I don't think it works anymore. It says package is moved and asks to install 'toGeojson' Package which doesn't support KMZ.

I've tried doing it with zip.js but stuck at zip.blobreader(blob) is not a constructor. I've tried usong jsZIP but still no luck.

Best Answer

If you include jsZip and toGeoJson in the header of your page and add this to the body

<input type="file" id="f">
<textarea id="output" rows="20" cols="70"></textarea>
<script>
    let getDom = xml => (new DOMParser()).parseFromString(xml, "text/xml")
    let getExtension = fileName => fileName.split(".").pop()

    let getKmlDom = (kmzFile) => {
        var zip = new JSZip()
        return zip.loadAsync(kmzFile)
            .then(zip => {
                let kmlDom = null
                zip.forEach((relPath, file) => {
                    if (getExtension(relPath) === "kml" && kmlDom === null) {
                        kmlDom = file.async("string").then(getDom)
                    }
                })
                return kmlDom || Promise.reject("No kml file found")
            });
    }
    var f = document.getElementById("f")
    f.addEventListener("change", e => {
        let geoJson = getKmlDom(e.target.files[0]).then(kmlDom => {
            let geoJsonObject = toGeoJSON.kml(kmlDom)
            return JSON.stringify(geoJsonObject)
        })
        geoJson.then(gj => document.getElementById("output").innerText = gj)
    })
</script>

you should be able to select a KMZ file and see the converted geoJson in the textbox. You can then test with a few local files. As mentioned by nmtoken and Christiaan Adams the conversion from KML til geojson depends on the exact content of the KML file. I don't know which tags are parsed by the toGeoJson library so you need to do some manual testing.

Here's a working demo JSFiddle.

Related Question