javascript - 将geoJSON加载到数据层时如何捕获异常

标签 javascript google-maps-api-3

我正在通过maps.data.loadGeoJson()将要素集合加载到 map 中。不幸的是,我的数据源偶尔会返回格式错误的 GeoJson 对象(features 为 null,而不是空数组)并引发 InvalidValueError。

该数据的示例:

{"type":"FeatureCollection","features":null} 

我希望能够捕获此错误,但由于 loadGeoJson() 是异步调用,因此在引发异常时我已经退出了 try block 。我读过( Is it possible to catch exceptions thrown in a JavaScript async callback? ),处理这个问题的方法是将 try/catch block 放在回调中。

听起来很合理,但我不确定应该在 try block 中设置什么条件。

map.data.loadGeoJson(url ,null,
    function(data){
        try(what_exactly){

        }catch(e){ }
    }
);

这是正确的方法,还是我走错了路?如果我坐错了船,哪条船是对的?

谢谢!

最佳答案

而不是使用 loadGeoJson ,使用addGeoJson .

  • loadGeoJson
    • Loads GeoJSON from a URL, and adds the features to the collection.
    • Return Value: None
  • addGeoJson
    • Adds GeoJSON features to the collection. Give this method a parsed JSON. The imported features are returned. Throws an exception if the GeoJSON could not be imported.
    • Return Value: Array<Data.Feature>

这是相关的SO question它提供了有关addGeoJson的代码实现。

希望这有帮助!

关于javascript - 将geoJSON加载到数据层时如何捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39258198/

相关文章:

javascript - 了解 Vscode 中的智能感知

javascript - Bootstrap 选项卡中的 Google map

google-maps-api-3 - 使用谷歌路线时更改信息窗口

javascript - 右键单击标记 - Google map V3

javascript - 在图 block 中绘制图像叠加表现得很奇怪

javascript - jQuery 根据输入值显示/隐藏选项

javascript - 在谷歌饼图中加载数据

javascript - 如何使用 Expo 在 React Native 中设置 cookie?

javascript - 在 div 中调用 javascript 函数

javascript - 如何扩展 'resize'事件?