上一章已经说完了如何调用地图服务,现在就要实现在地图上打点、连线的功能。
1、打点,确定经纬度并在这经纬度上实现放图标、备注等功能。,直接上代码
// 存放图标
const vector= new ol.layer.Vector({
source: new ol.source.Vector({
wrapX: false
})
});
// 创建一个Feature,并设置好在地图上的位置
var anchor1 = new ol.Feature({
geometry: new ol.geom.Point([106.542792, 29.563206]),
name: '杆塔1',
id: 1
});
// 设置样式,在样式中就可以设置图标
anchor1.setStyle(new ol.style.Style({
image: new ol.style.Icon({
src: 'https://openlayers.org/en/latest/examples/data/icon.png',
scale: 1
}),
text: new ol.style.Text({
font: '12px Microsoft YaHei',
text: "杆塔1",
fill: new ol.style.Fill({
color: '#222',
paddingTop: "30px"
}),
offsetX: 0,
offsetY: -30,//调整相对位置
})
}));
//画线
var coordinates = new Array();
coordinates[0] = [106.542792, 29.563206];
coordinates[1] = [107.27466, 29.368997];
coordinates[2] = [107.22158866134038, 30.576344467369506];
coordinates[3] = [108.438237, 31.802508];
var feature = new ol.Feature({
geometry: new ol.geom.LineString(coordinates),
});
feature.setStyle(new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.1)'
}),
stroke: new ol.style.Stroke({
color: 'red',
width: 2
}),
text: new ol.style.Text({
font: '12px Microsoft YaHei',
text: "测试线路1",
fill: new ol.style.Fill({
color: '#222'
}),
offset: [0, 0],
rotation: -0.85
}),
}));
vector.getSource().addFeatures([anchor1,feature ]);
1、vector:相当于一个图层,存放图标的feature,feature就是设置位置,然后设置样式,image是引用图标,text是文字,每个位置对应一个feature,然后把这些feature放进vector的source。这个vector放进map的layers里。