
1.png
這個(gè)問(wèn)題是因?yàn)楫惓^(qū)域的數(shù)據(jù)沒(méi)有單獨(dú)拎出來(lái),而是跟周?chē)缆窋?shù)據(jù)一并返回的。如何知道這一點(diǎn)呢?我們可以對(duì)geojson進(jìn)行拾取,當(dāng)點(diǎn)擊某一部分時(shí),讓其高亮顯示。
import { Component, ElementRef, ViewChild } from '@angular/core';
import * as mapboxgl from 'mapbox-gl';
import MapboxDraw from '@mapbox/mapbox-gl-draw';
import * as turf from '@turf/turf';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.scss'],
})
export class MapComponent {
@ViewChild('map')
private mapContainer!: ElementRef<HTMLElement>;
constructor() {}
async getGeojson() {
const json = await fetch('/assets/202412021426471681.geojson').then((response) => response.json());
json.features.map((feature, index) => {
feature.properties = { id: index };//便于拾取篩選
});
return json;
}
async ngAfterViewInit() {
const geojson = await this.getGeojson();
(mapboxgl as any).accessToken = 'default_token'; //隨便寫(xiě)
const map = new mapboxgl.Map({
container: this.mapContainer.nativeElement,
projection: 'globe', // 設(shè)置為球體投影
style: {
version: 8, //這個(gè)不能亂寫(xiě)
sources: {}, //置空
layers: [
{
id: 'background',
type: 'background',
paint: { 'background-color': 'white' },
}, //背景為白色的球
],
},
center: [0, 0], // 初始位置
zoom: 0, // 初始縮放級(jí)別
});
map.on('load', function () {
// 添加數(shù)據(jù)源
map.addSource('polygon-source', {
type: 'geojson',
data: geojson,
});
// 添加圖層
map.addLayer({
id: 'polygon-layer',
type: 'fill',
source: 'polygon-source',
paint: {
'fill-color': '#0080ff', // 多邊形填充顏色
'fill-opacity': 0.5, // 多邊形透明度
},
});
});
map.flyTo({
center: [117.30395791760482, 31.70632373320954],
zoom: 12,
});
map.on('click', 'polygon-layer', (e) => {
const clickPoint = [e.lngLat.lng, e.lngLat.lat];
const point = turf.point(clickPoint);
let foundPolygon = null;
geojson.features.map((feature) => {
const isInside = turf.booleanPointInPolygon(point, feature.geometry);
// console.log(isInside, 'isInside');
if (isInside) {
foundPolygon = feature;
const targetFeatureId = feature.properties.id;
console.log('found>>>', foundPolygon);
map.setPaintProperty('polygon-layer', 'fill-color', [
'case',
['==', ['get', 'id'], targetFeatureId], // 如果特征的 id 屬性等于目標(biāo) ID
'#ff0000', // 則設(shè)置顏色為紅色
'#0080ff', // 否則保持初始顏色
]);
}
});
});
const draw = new MapboxDraw({
displayControlsDefault: false,
controls: {
polygon: true,
trash: true,
},
});
map.addControl(draw);
}
}

2.png
可以看到,異常區(qū)域的數(shù)據(jù),確實(shí)跟周?chē)缆肥且惑w的。正確的數(shù)據(jù)是這樣的:

3.png