** 最近使用openlayer添加网格,需要加载文字标注,在这里遇见一个问题:当你添加面坐标是字符串时,则文字标注加载不上去。**
图层样式:
style: function (feat) {
var 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: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ffcc33'
})
}),
text: new ol.style.Text({
text: feat.get('info').SYSTEM_ID,
font: '10px sans-serif',
textAlign: "center",
textBaseline: "middle",
//font: 'verdana',
fill: new ol.style.Fill({
color: "#ff0000"
}),
backgroundFill: new ol.style.Fill({
color: "#ff0000"
}),
font: "10px sans-serif",
stroke: new ol.style.Stroke({
color: "#ffffff"
// width: 3
}),
offsetX: parseInt(0, 10),
offsetY: parseInt(0, 10),
placement: "point", //point 则自动计算面的中心k点然后标注 line 则根据面要素的边进行标注
overflow: false //超出面的部分不显示
})
})
feat.setStyle(style);
},
添加面图层:
function drawCameraGridToMap(cameraGridArr) {
vector.getSource().clear();
var pattern = /\d+.\d*/g;
for (var i = 0; i < cameraGridArr.length; i++) {
var oldCodernit = cameraGridArr[i].SHAPE.match(pattern);
var newCoords = [];
for (var j = 0; j < oldCodernit.length; j++) {
if (j % 2 == 0) {
newCoords.push([oldCodernit[j] , oldCodernit[j + 1]]);
}
}
var polygon = new ol.geom.Polygon([newCoords]);
var feature = new ol.Feature({
geometry: polygon
});
feature.setId(cameraGridArr[i].JL_ID);
feature.set('info', cameraGridArr[i]);
vector.getSource().addFeature(feature);
}
}
由正则表达式提取的坐标是字符串格式的,导致文字表添加不上(console.log(feat.getStyle().getText().getText())可以获取到text)。但是在这里又有一个问题,当添加的是点图层时,即使点坐标是字符串时也能够添加上标注,what!这时面图层加标注只需把坐标处理时加上parseFloat就欧克了,简直不要太简单!(newCoords.push([parseFloat(oldCodernit[j]) , parseFloat(oldCodernit[j + 1])]);)