起因是ol原生的位置转换使用起来有误差,自己手搓一个
// 定义一个函数来计算两点之间的直线距离
calculateDistance(point1, point2) {
const deltaX = point2[0] - point1[0]; // 计算横向距离差
const deltaY = point2[1] - point1[1]; // 计算纵向距离差
const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY); // 应用欧几里得距离公式
return distance;
},
数据编码格式转换
import { transform, get } from "ol/proj";
//坐标,源投影,目标投影
transform(coordinate, 'EPSG:4326', 'EPSG:3857')
//坐标,源投影,目标投影
transform(coordinate, 'EPSG:4326', 'EPSG:3857')
//如果是 geoJSON数据格式转换,则MultiPolygon和Polygon方法可以直接点出transform方法直接转换。
geometry: new MultiPolygon(
lineData.geometry.coordinates
).transform("EPSG:4326", "EPSG:3857")
//或者
geometry: new Polygon(
lineData.geometry.coordinates
).transform("EPSG:4326", "EPSG:3857")
//使用 new GeoJSON().readFeatures方法时,默认的是4326编码,如果想转换编码格式的话加一个参数
const fts = new GeoJSON().readFeatures(data, {
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857',
});
设置弹窗偏移,默认的弹窗是左上角出现在我们的点击位置,不太美观需要相对调整一下
import { Overlay} from 'ol';
const popupOverlay = new Overlay({
element: document.getElementById("contextmenu"),
positioning: 'bottom-center',
stopEvent: false,
visible: false,
offset: [-150, -200], // 弹窗位置的偏移量,向上偏移 200 像素,向右150
});
持续更新