Turf.js查找使用Mapbox GL JS加载的数据的边界框? [英] Turf.js to find bounding box of data loaded with Mapbox GL JS?

查看:104
本文介绍了Turf.js查找使用Mapbox GL JS加载的数据的边界框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Mapbox GL JS从某些页面上的外部URL加载GeoJSON.我想使地图自动适应要加载的多边形的边界.

I'm using Mapbox GL JS to load in GeoJSON from an external URL on some pages. I would like to automatically fit the map to the boundaries of the polygon I'm loading.

我知道 turf.js的bbox方法可以帮助解决此问题,但我不确定如何将GeoJSON放入 turf.bbox 调用中.

I understand that turf.js's bbox method can help with this, but I'm not sure how to get the GeoJSON into the turf.bbox call.

这是我现在的代码:

map.addSource('mylayer', {
    type: 'geojson',
    data: '/boundaries.geojson'
});
map.addLayer({
    "id": "mylayer",
    "type": "fill",
    "source": "mylayer",
    'paint': {
        'fill-color': '#088',
        'fill-opacity': 0.6
    }
});
var bbox = turf.bbox('mylayer');
map.fitBounds(bbox, {padding: 20});

但是它失败,并显示 turf.min.js:1未捕获的错误:未知的几何类型.文档说, bbox 想要任何GeoJSON对象".

But it fails with turf.min.js:1 Uncaught Error: Unknown Geometry Type. The docs say that bbox wants "any GeoJSON object".

如何正确执行此操作?我显然宁愿不要两次加载外部文件.

How do I do this correctly? I'd obviously rather not load the external file twice.

推荐答案

1)从远程源加载数据是异步的.也就是说,您正在尝试在加载数据之前对其进行分析.

1) Loading data from a remote source is asynchronous. That is, you are trying to analyze the data before it was loaded.

因此,您需要处理 sourcedata 事件.

So you need handle the sourcedata event.

2) bbox 函数的输入参数是一个有效的 GeoJson对象 .

3)如前所述, Turf.js 不了解有关 Mapbox 的任何信息,因此,您还需要从源读取加载的数据.

3) As already noted, the Turf.js does not know anything about the Mapbox, so you need to read the loaded data from the source in addition.

4)例如:

map.addSource('mylayer', {
    type: 'geojson',
    data: '/boundaries.geojson'
});
map.addLayer({
    "id": "mylayer",
    "type": "fill",
    "source": "mylayer",
    'paint': {
        'fill-color': '#088',
        'fill-opacity': 0.6
    }
});

map.on('sourcedata', function (e) {
  if (e.sourceId !== 'mylayer' || !e.isSourceLoaded) return
  var f = map.querySourceFeatures('mylayer')
  if (f.length === 0) return
  var bbox = turf.bbox({
    type: 'FeatureCollection',
    features: f
  });
  map.fitBounds(bbox, {padding: 20});    
})

这篇关于Turf.js查找使用Mapbox GL JS加载的数据的边界框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆