1.根据坐标在地图上添加一个要素
如果只有点的坐标,我们需要自己造一个geoJson数据,如下所示:
/**
* @description 创建点要素
* @param {*Array} coordinate 传入的坐标
*/
createPoint(coordinate) {
var data = {
type: "Feature",
geometry: {
type: "Point",// 这里可以不同的类型,来绘制不同的要素
coordinates: coordinate,
},
};
return data;
},
这个方法会返回一个格式形如geoJson的对象,我们还需要用format方法来把他转为真正的geoJson对象。
let feat = this.createPoint("输入坐标"); // 获取点的坐标
let Location = new ol.format.GeoJSON().readFeatures(feat); // 把坐标转化为geoJson对象
最后把生成的要素添加到目标图层上就行了
this.vecLayer.getSource().addFeatures(Location);
2.在地图上绘制要素
/**
* @description 在地图上画要素
*/
markPoint() {
//创建并把交互器添加到地图上
this.draw = new ol.interaction.Draw({
source: this.vecLayer.getSource(),
type: "Point",//这里更改要画对象的要素
style: new ol.style.Style({
fill: new ol.style.Fill({
color: "rgba(255, 255, 255, 0.2)",
}),
stroke: new ol.style.Stroke({
color: "#ffcc33",
width: 12,
}),
}),
});
this.map.addInteraction(this.draw);
//监听绘画交互,画完之后移除画线功能
this.draw.on("drawend", (e) => {
console.log(e);//e是对象,包含所有的数据
this.latitude = e.target.Wv[0];
this.longitude = e.target.Wv[1];
this.map.removeInteraction(this.draw);
});
}
},
3.移动地图视图到规定的位置
/**
* @description 移动地图至geom处
* @param {*Array} geom 地图中心的坐标
*/
gotoLocal(geom) {
this.map.getView().animate({
center: geom, // 要移动的位置
duration: 300, // 过度时间 毫秒值
});
},
// 平常的写法应该把this.map 写成map.getMap().getView() this.map是我司业务代码的简便写法
除此以外还有
this.map.getView().setZoom("层级数") 改变地图层级
4.前后端使用不同坐标系时单个geojson对象的坐标转换
coordinatesSwitchAndDarw(feature) {
this.vecLayer.getSource().clear();// 清除图层上原来的要素
let feat = new ol.format.GeoJSON().readFeature(feature); // 读取geoJson对象
const theGeom = feat.getGeometry();// 获取几何要素
if (!theGeom) {
return;
}
feat.getGeometry().transform("EPSG:4326", "EPSG:3857");// 坐标转换(转变前坐标系,转变后的坐标系)
let geom = [feat.A.geometry.flatCoordinates[0], feat.A.geometry.flatCoordinates[1]]; // 接收转变后的坐标系
this.gotoLocal(geom);
this.vecLayer.getSource().addFeatures([feat]);
},
这里的getLocal就是上面3中的getLocal()