import "ol/ol.css";
import GeoJSON from "ol/format/GeoJSON";
import HeatmapLayer from "ol/layer/Heatmap";
import Layer from "ol/layer/Layer";
import Source from "ol/source/Source";
import VectorSource from "ol/source/Vector";
import View from "ol/View";
import { fromLonLat, toLonLat } from "ol/proj";
import Map from "ol/Map";
const center = [8.330867392650134, 47.28077320363727];
let initZoom = 1;
export default {
data() {
return {
globalBounds: [],
map: {},
};
},
mounted() {
this.initMap();
},
methods: {
updates(value) {
this.globalBounds = value;
// console.log("监听更新的值:", this.globalBounds, 999999999999);
},
initMap() {
let self = this;
const mbMap = new mapboxgl.Map({
style: "http://172.0.0.1:1008/styles/basic-preview/style.json", //地图服务的数据地址
attributionControl: false,
boxZoom: false,
center: center,
container: "map",
doubleClickZoom: false,
dragPan: false,
dragRotate: false,
interactive: false,
keyboard: false,
pitchWithRotate: false,
scrollZoom: false,
touchZoomRotate: false,
});
let heat1 = "/data/geojson/world-cities.geojson";
let heatmap = "/data/geojson/world-cities-ii.geojosn";
let heatsource = new VectorSource({
url: heat1,
format: new GeoJSON(),
});
//加载热力图
let cities = new HeatmapLayer({
source: heatsource,
weight: function (feature) {
return feature.get("population") / 1e7;
},
radius: 15,
blur: 15,
});
const mbLayer = new Layer({
render: function (frameState) {
const canvas = mbMap.getCanvas();
const viewState = frameState.viewState;
const visible = mbLayer.getVisible();
canvas.style.display = visible ? "block" : "none";
canvas.style.position = "absolute";
const opacity = mbLayer.getOpacity();
canvas.style.opacity = opacity;
const rotation = viewState.rotation;
mbMap.jumpTo({
center: toLonLat(viewState.center),
zoom: viewState.zoom - 1,
bearing: (-rotation * 180) / Math.PI,
animate: false,
});
if (mbMap._frame) {
mbMap._frame.cancel();
mbMap._frame = null;
}
mbMap._render();
return canvas;
},
});
//监听地图变化
mbMap.on("moveend", () => {
// 获取当前缩放级别
const zoom = mbMap.getZoom();
let zoomSize = 1;
if (zoom < 7) {
zoomSize = 1;
} else if (zoom >= 7 && zoom < 9) {
zoomSize = 2;
} else if (zoom >= 9 && zoom < 11) {
zoomSize = 3;
} else if (zoom >= 11) {
zoomSize = 4;
}
if (initZoom != zoomSize) {
initZoom = zoomSize;
if (cities) {
//动态刷新热力图数据
heatsource.setUrl(heatmap);
heatsource.refresh();
}
}
// 获取当前范围
const bounds = mbMap.getBounds();
// console.log(bounds, "左下:", bounds._ne, "右上:", bounds._sw);
self.updates([
[bounds._ne.lat, bounds._ne.lng],
[bounds._sw.lat, bounds._sw.lng],
]);
});
//挂载地图
var map = new Map({
target: "map",
view: new View({
center: fromLonLat(center),
zoom: 4,
}),
layers: [mbLayer, cities],
});
},
},
};
.map {
width: 100%;
height: 600px;
}