Question

I need to load a zip file in OpenLayers via OpenLayers.Protocol.HTTP. I want to load it and unzip it with the help of jszip. Since I want to load binary data I have to change the mimeType of the XMLHttpRequest. A jszip example says it works like this:

var xhr1 = new XMLHttpRequest();
  xhr1.open('GET', '../test/ref/text.zip', true);
  if (xhr1.overrideMimeType) {
    xhr1.overrideMimeType('text/plain; charset=x-user-defined');
  }

  xhr1.onreadystatechange = function(e) {
    if (this.readyState == 4 && this.status == 200) {
      var zip = new JSZip(this.responseText);
      var elt = document.getElementById('xhr1_way');
      elt.innerHTML = "<p>loaded ! (as a " + (typeof this.responseText) + ")</p>";
      elt.innerHTML += "<p>Content = " + zip.file("Hello.txt").asText();
    }
  };

Unfortunately the XMLHttpRequest class OpenLayers uses (OpenLayers.Request.XMLHttpRequest) has no overrideMimeType function. When I try to unzip the loaded data without setting the mime type I get the error "End of data reached (data length = 23798955, asked index = 24968701). Corrupted zip ?", so it looks like the zip wasn't loaded correctly. Any suggestions how to solve this problem?

Was it helpful?

Solution

The restriction in Openlayer is most likely implemented on purpose, because binary request out of JavaScript simply are not supported by all browsers (guess which one is not up to it).

You are not required to use OpenLayer's HTTP capabilities to load data. Do your own request with your favorite JS framework (here is an example) and then load your data with whatever data type you use.

var zip = new JSZip(this.responseText);
var jsonFormat = new OpenLayers.Format.JSON();
var jsonData = jsonFormat.read(zip.file("Hello.txt").asText());
var gson = jsonData.somewhere.is.my.gson;
var layer = new OpenLayers.Layer.Vector();
map.addLayer(layer);
layer.addFeatures(geojson_format.read(gson)); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top