mardi 5 novembre 2019

IF not working after ELSE has been accepted (potential Leaflet.Draw issue)

I have a Leaflet map that uses the Leaflet.Draw library and allows a user to draw a geoJSON polygon and download the file (after it has been converted to .KML format). I had an issue where the download function would still run if no polygon was drawn, so I tried to fix that using an IF/ELSE statement that looks at the length of the geoJSON file.

document.getElementById('export').onclick = function(e) {

  //extract GeoJson from featureGroup
  var data = featureGroup.toGeoJSON();
  console.log(data.features.length);    

  if (data.features.length === 0) {
    alert('Your drawn feature is not valid!');              
  } else {
    //convert to KML
    var kml = tokml(data);

    //convert to dataURL format
    var convertedData = 'application/vnd.google-earth.kml+xml;charset=utf-8,' + 
    encodeURIComponent(kml);

    //create export
    document.getElementById('export').setAttribute('href', 'data:' + convertedData);
    document.getElementById('export').setAttribute('download','3DroneMapping_AOI.kml');
  }
} 

At first the above code seemed to work well. Clicking the download button without drawing a polygon feature would log 0 to the console and the alert would appear. Where as drawing a polygon feature and clicking the download button would log 1 to the console and the file would download.

The issue happens after drawing a polygon feature, downloading it and the deleting it with the delete button:

document.getElementById('delete').onclick = function(e) {           
  featureGroup.clearLayers();
}

Now that the polygon feature has been deleted, the download button should trigger the alert again. But what happens is that although the console still logs 0 and the alert is triggered, after clicking "ok" on the alert the ELSE section of the code still runs and the same geoJSON file that was apparently "cleared" still downloads (contains the same coordinates).

Is this a simple mistake in my code, or is it something related to the Leaflet.Draw library?

Thanks

Aucun commentaire:

Enregistrer un commentaire