0

I'm working on an app where a user can upload a KML file and it renders the paths on screen using Leaflet, toGeoJSON & Angular-Leaflet-Directive.

I use toGeoJSON.kml() to transform the KML text to a GeoJSON object and then pass it to Leaflet for rendering. This works great if the KML is valid. However, if the KML is malformed, it doesn't work so great. toGeoJSON continues to render the data into an object, ignoring any errors that occur.

var pathData = toGeoJSON.kml(kmlDom);
var latlng = [];

for (var feature in pathData.features) {
    var paths = pathData.features[feature].geometry.coordinates;
    if (paths.length > 1) {
        for (var path in paths) {
           var prospectiveCoords = pathData.features[feature].geometry.coordinates[path];
           var coordinate = L.GeoJSON.coordsToLatLng(prospectiveCoords);
            latlng.push(coordinate);
        }
    }
}
try {
    map.fitBounds(latlng); //Instance of L.getMap()

    angular.extend($scope, {
        geojson : {
            data : pathData,
            style : {
                stroke : true,
                weight : 5
            }
        }
    });

} catch (e) {
    $log.error(e.message);
    $window.alert(e.message);
}

In my specific issue, if there is an error in the pathData variable, it triggers the exception in LatLng line 7:

L.LatLng = function (lat, lng, alt) {
    if (isNaN(lat) || isNaN(lng)) {
        throw new Error('Invalid LatLng object: (' + lat + ', ' + lng +   ')');
    } 

    ...

Unfortunately, this error does not get trapped by my catch block and Leaflet continues to render the map tiles without the path overlay, and the only notice the user gets is inside the console. My goal is to have a more visible user notice when an invalid file is uploaded.

Is it possible to intercept the error at the application level?

Jason
  • 11,263
  • 21
  • 87
  • 181

1 Answers1

0

Is this code inside a callback function or so? do you get the geojson data through an ajax call? Asynchronous callback methods could do the error trapping very tricky and not in the order it is expected. This previous post it is very interesting: Catch statement does not catch thrown error

Community
  • 1
  • 1
rossig7
  • 81
  • 1
  • 10
  • Hmm, interesting suggestion. This code is within a promise success handler for leafletData.getMap() and the geojson data comes in from a non-async service call, so in theory any async calls are already resolved by the time this code block executes. I just raised this issue to the respective github repos and will update on any resolution. – Jason Jan 17 '16 at 19:04