[GIS] Using MSID/MID with leaflet to display Google My Maps data

google mapsjavascriptkmzleaflet

I'm wondering if there is a way to display MSID/MID with leaflet.

I found this forum below;
Any way I can load KML data from Google maps (again) via JS API?

KMZs work fantastically with the arcgis and google API (kmlLayer) but I can't seem to find any information on using a kmz with leaflet.
I'd prefer not having to Unzip locally, and omnivore does not appear to work with KMZs.

Best Answer

I haven't got any solutions for accessing KMZ files via a My Maps MSID/MID in Leaflet. However, in general, to load a KMZ file in Leaflet, you can use JSZip (along with the getBinaryContent method of JSZipUtils) to extract the KML, then Leaflet Omnivore to parse the result.

JSZip will produce an object containing all the files in an archive, and you can select an individual file either by name or with the file(regex) method. You can use file(/.*\.kml/)[0] to select the first file with a .kml extension. Then to read the file as text, you would use either the asText method (in version 2.x of JSZip) or the async("string") method (in version 3.x). Once you have the kml as text, you can use Leaflet Omnivore's .kml.parse method to read it into a Leaflet layer. For version 2.x (which I find more straightforward), the whole thing would look like this:

var kmzUrl = *your URL here*;

JSZipUtils.getBinaryContent(kmzUrl, function(e, d) {
  try {
    var z = new JSZip(d);
    var k = z.file(/.*\.kml/)[0].asText();
    var p = omnivore.kml.parse(k).addTo(map);
    p.eachLayer(function(layer){
      layer.bindPopup(layer.feature.properties.description); //or whatever
    })
  } catch (e) {
    alert(e);
  }
});

Example fiddle here: http://jsfiddle.net/nathansnider/26vagt77/

For version 3.x, it would look like this:

var kmzUrl = *your URL here*;

JSZipUtils.getBinaryContent(kmzUrl, function(err, data) {
  if (err) {
    alert(err);
    return;
  }
  try {
    JSZip.loadAsync(data)
      .then(function(zip) {
        return zip.file(/.*\.kml/)[0].async("string");
      })
      .then(function success(text) {
          var p = omnivore.kml.parse(text).addTo(map);
          p.eachLayer(function(layer) {
            layer.bindPopup(layer.feature.properties.description); //or whatever
          });
        },
        function error(e) {
          alert(e);
        });
  } catch (e) {
    alert(e);
  }
});

Example fiddle: http://jsfiddle.net/nathansnider/adxcapeo/