我正在通过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/