boundsOfGeoJSON
扫描任意 GeoJSON 的全部坐标求包围盒,可直接传给 map.fitBounds。
简介
boundsOfGeoJSON 扫描任意 GeoJSON(要素 / 几何 / 集合 / 几何集合)的全部坐标,求西南、东北角包围盒,返回可直接传给 map.fitBounds 的元组;无坐标时返回 undefined。常用于把视野缩放到一组数据的范围。useMapboxCamera 的 fitBounds 接受 GeoJSON 时即内部调用它。
从 @movk/mapbox/utils/geometry 导入(非自动导入)。
用法
求折线包围盒并缩放到该范围,同时用矩形可视化包围盒:
<script setup lang="ts">
import { boundsOfGeoJSON } from '@movk/mapbox/utils/geometry'
import type { FeatureCollection } from 'geojson'
const mapId = 'geometry-bounds-demo'
const data: FeatureCollection = {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
properties: {},
geometry: {
type: 'LineString',
coordinates: [
[116.39, 39.91],
[117.2, 39.13],
[118.18, 39.63],
[119.6, 39.94]
]
}
}
]
}
const bounds = boundsOfGeoJSON(data)
// 把包围盒元组转成矩形要素用于可视化
const bbox: FeatureCollection | undefined = bounds && {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
properties: {},
geometry: {
type: 'Polygon',
coordinates: [
[
[bounds[0][0], bounds[0][1]],
[bounds[1][0], bounds[0][1]],
[bounds[1][0], bounds[1][1]],
[bounds[0][0], bounds[1][1]],
[bounds[0][0], bounds[0][1]]
]
]
}
}
]
}
const { fitBounds } = useMapboxCamera({ mapId })
</script>
<template>
<div class="relative h-115 w-full overflow-hidden rounded-(--ui-radius) border border-default">
<MapboxMap
:map-id="mapId"
:options="{ style: 'mapbox://styles/mapbox/light-v11', center: [117.5, 39.6], zoom: 6 }"
>
<MapboxLayer
layer-id="geo-line"
type="line"
:source="{ type: 'geojson', data }"
:paint="{ 'line-color': '#8b5cf6', 'line-width': 3 }"
/>
<MapboxSource v-if="bbox" source-id="geo-bbox" :source="{ type: 'geojson', data: bbox }">
<MapboxLayer
layer-id="geo-bbox-line"
type="line"
source="geo-bbox"
:paint="{ 'line-color': '#f59e0b', 'line-width': 1, 'line-dasharray': [2, 2] }"
/>
</MapboxSource>
</MapboxMap>
<div class="absolute left-2 top-2 z-10">
<UButton size="sm" :disabled="!bounds" @click="bounds && fitBounds(bounds, { padding: 40 })">
缩放到包围盒
</UButton>
</div>
</div>
</template>
API
boundsOfGeoJSON()
求 GeoJSON 包围盒。
input
GeoJSON required
任意 GeoJSON 对象。
返回 LngLatBoundsTuple | undefined:[[west, south], [east, north]] 元组;无坐标时为 undefined。
LngLatBoundsTuple
西南 / 东北角包围盒:[[number, number], [number, number]],可直接传给 map.fitBounds。
Changelog
No recent changes