[英]Mapbox GL JS: change zoom depending on search range
也許這是一個愚蠢的問題,但無論如何,
在我的應用程序的搜索頁面上,我有一個范圍輸入來確定搜索范圍(最小 5 公里,最大 50 公里)。 根據設置值,我想更改 MapBox GL map 中的當前縮放,使其僅顯示在此輸入中設置的區域(如果搜索范圍約為 10 公里,我應該只看到一個 map 扇區半徑 10 公里。)。 我的數學有點弱,這使我無法找到這種相關性。
提前致謝。
因此,您希望 map 區域包含一個以公里為單位的大小的圓。
一種簡單(但有點臃腫)的方法是使用Turf 。
const rangeCircle) = turf.circle(map.getCenter().toArray(), radius, { units: 'kilometers' });
map.fitBounds(rangeCircle)
這樣您就不需要顯式計算縮放級別 - Mapbox 的fitBounds()
會為您計算出來。
最后我想出了如何使用 Turf.js 做到這一點。 這是我的解決方案:
function fitToRadius(radius) {
const { lng, lat } = mapbox.getCenter();
const center = [lng, lat];
const rangeCircle = turf.circle(
center,
radius,
{ units: "kilometers"}
);
const [coordinates] = rangeCircle.geometry.coordinates;
const bounds = new mapboxgl.LngLatBounds(
coordinates[0],
coordinates[0]
);
/* Extend the 'LngLatBounds'
to include every coordinate in the bounds result. */
coordinates.forEach((coord) => bounds.extend(coord));
mapbox.fitBounds(bounds);
}
感謝Steve Bennett對 Turf.js 的暗示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.