Leaflet - 可以捕获应用程序

时间:2016-01-16 18:58:29

标签: javascript error-handling try-catch leaflet

我正在开发一个用户可以上传KML文件的应用,并使用LeaflettoGeoJSON& Angular-Leaflet-Directive

我使用toGeoJSON.kml()将KML文本转换为GeoJSON对象,然后将其传递给Leaflet进行渲染。如果KML有效,这很有用。但是,如果KML格式错误,它就不会那么好用。 toGeoJSON继续将数据呈现为对象,忽略发生的任何错误。

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);
}

在我的具体问题中,如果pathData变量中存在错误,则会在LatLng第7行触发异常:

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

    ...

不幸的是,这个错误不会被我的catch块所困,并且Leaflet继续呈现没有路径覆盖的地图图块,并且用户获得的唯一通知是在控制台内。我的目标是在上传无效文件时提供更明显的用户通知。

是否可以在应用程序级别拦截错误?

1 个答案:

答案 0 :(得分:0)

此代码是否在回调函数内?你通过ajax调用获得geojson数据吗?异步回调方法可能会使错误捕获非常棘手,而不是按预期的顺序进行。 这篇上一篇文章非常有趣: Catch statement does not catch thrown error