我将在这里放置部分代码,这对于理解问题很重要。
const createHex = (lat: any, lng: any) => {
const cell = latLngToCell(lng, lat, 1);
const coords = cellToBoundary(cell).map((c) => [c[1], c[0]]);
const polygon = new Polygon([coords]);
const feature = new Feature(polygon);
vectorSource.addFeature(feature);
};
const map = new Map({
target: 'map',
layers: [
new TileLayer({
source: new TileJSON({
url: 'https://api.maptiler.com/maps/satellite/256/tiles.json?key=yFxxWLuQf6QipClqNF0n',
crossOrigin: 'anonymous'
})
})
],
view: new View({
center: [0, 0],
zoom: 2,
projection: 'EPSG:4326'
})
});
map.on('click', (e) => {
createHex(e.coordinate[0], e.coordinate[1]);
});
为了获得最佳结果,穿过反子午线的多边形应该被分割以形成一个 MultiPolygon,但是这样做并不简单,因为您需要计算交点(使用诸如 turf.js 之类的实用程序)。只需使用扩展坐标使多边形连续即可获得足够的结果
let coords = cellToBoundary(cell).map((c) => [c[1], c[0]]);
if (coords.some((c) => c[0] < -90) && coords.some((c) => c[0] > 90)) {
coords = coords.map((c) => [c[0] + (c[0] < -90 ? 360 : 0), c[1]]
}