import { Component } from '@angular/core';
import mapboxgl from 'mapbox-gl';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.scss'],
})
export class MapComponent {
map: any;
constructor() {}
ngOnInit(): void {
mapboxgl.accessToken = 'xxxxxxxxxxx';
this.map = new mapboxgl.Map({
container: 'mapboxDiv', // container id
style: 'mapbox://styles/mapbox/light-v11',
center: [116.39880632, 38.90487972],
minZoom: 0,
maxZoom: 17,
});
this.map.on('load', () => {
this.init();
this.drawGrid();
});
this.map.on('styledata', () => {
this.map.resize();
});
this.map.on('zoomend', function () {
const range = Math.floor(this.getZoom());
console.log('range级数>>>', range);
});
}
init() {
//初始化
this.map.addSource('grid-square', {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: [],
},
});
this.map.addLayer({
id: 'grid-square',
type: 'fill',
source: 'grid-square',
paint: {
'fill-color': 'yellow',
'fill-opacity': 1,
},
});
}
drawGrid() {
//画网格
const bounds = this.map.getBounds();
const west = Math.floor(bounds.getWest());
const east = Math.floor(bounds.getEast());
const south = Math.floor(bounds.getSouth());
const north = Math.floor(bounds.getNorth());
const arr = [];
for (let i = west; i <= east; i += 10) {
arr.push({
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: [
[i, north],
[i, south],
],
},
});
}
for (let i = south; i < north; i += 10) {
arr.push({
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: [
[west, i],
[east, i],
],
},
});
}
this.map.getSource('grid-square').setData({
type: 'FeatureCollection',
features: arr,
});
}
}
1.png
网友评论