Search code examples
javascriptleafletkmz

Input KMZ files into the Leaflet map


Basing on the query posted a while ago here:

Using KMZ file in Leaflet Map

I get to the GitHub repository:

https://github.com/engrabid411/kmzol3

from where I used the code for my own files.

Basically the code doesn't work at all in the repository, showing a blank map only.

However, even if you implement your own file it doesn't change.

The code looks like this:

 var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  controls: ol.control.defaults({
    attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
      collapsible: false
    })
  }),
  target: 'map',
  view: new ol.View({
    center: [0, 0],
    zoom: 2
  })
});

var nestedKMZData = new Array();
var nestedKMZLinks = new Array();
var hasOwnProperty = Object.prototype.hasOwnProperty;

function isEmpty(obj) {
    if (obj == null)return true;
    if (obj.length > 0)return false;
    if (obj.length === 0)return true;
    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) return false;
    }
    return true;
}
var deferred = $.Deferred();
function readKMZ( url , callback){

    if (!/^(?:f|ht)tps?\:\/\//.test(url)) {
        url = "http://" + url;
    }
    JSZipUtils.getBinaryContent(
        'proxy/index.php?url='+url, 
        function(err, data) {
          if(err) {
            throw err; 
          }

        var zip = new JSZip(data);
        for(f in zip.files){
            var extractData = zip.files[f].asText(); 

            if (window.DOMParser) {
              parser=new DOMParser();
              xmlDoc=parser.parseFromString(extractData,"text/xml");
            } else { // Internet Explorer
              xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
              xmlDoc.async=false;
              xmlDoc.loadXML(extractData); 
            }


            var NetworkLink = xmlDoc.getElementsByTagName('NetworkLink');

            if(isEmpty(NetworkLink) == true){
                nestedKMZData.push(extractData);
                deferred.resolve(nestedKMZData);
            }


            for(var L in NetworkLink){

                if(typeof NetworkLink[L] === "object" ){
                    deferred.notify();
                    var Link = NetworkLink[L].getElementsByTagName('Link');
                    var href = Link[0].getElementsByTagName('href')[0].innerHTML;

                    readKMZ(href);

                }

            }

        }
    }); 
    return deferred.promise();
}

  var data = readKMZ('http://xjubier.free.fr/download/GE/en/TSE_2001_06_21.kmz');
data.done(function(d){ console.log(d);});

After running, the console says:

Access to XMLHttpRequest at 'http://xjubier.free.fr/download/GE/en/TSE_2001_06_21.kmz' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

and also:

Uncaught Error: InvalidStateError: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'arraybuffer'). at XMLHttpRequest.xhr.onreadystatechange (jszip-utils.js:93)

In my humble opinion, the error is here:

function readKMZ( url , callback){

    if (!/^(?:f|ht)tps?\:\/\//.test(url)) {
        url = "http://" + url;
    }
    JSZipUtils.getBinaryContent(
        'proxy/index.php?url='+url, 
        function(err, data) {
          if(err) {
            throw err; 
          }

where I don't understand 'proxy/index.php?url='+url, . Is there some solution to make this code running? I am asking also in terms of .kmz files placed on my localhost instead of web server.


Solution

  • The 1st code you show is made for OpenLayers.

    Then the 2nd code you show seems to rely on a PHP backend server to act as a proxy to download the target KMZ file, maybe to workaround CORS issue.

    It also seems to contain a custom algorithm to fetch nested linked files.

    If your objective is just to retrieve a simple KMZ file that you have control on, unzip it and parse its KML content, then you do not need at all such proxy and custom parsing: - retrieve the KMZ file as binary through AJAX (with fetch, jQuery, etc.) - unzip the file (JSZip...) - find the embedded KML content and parse it (e.g. with leaflet omnivore kml.parse)