我需要绘制一条连接点到其标签的线。像这样:
' Y'有坐标,使用offSet标签在屏幕上的不同位置。我也可以通过改变它的偏移量来拖动标签,我需要在我这样做时调整线条以便它们保持连接。
有没有办法在地图上画线而不提供坐标?因为我只有一组坐标和一个偏移。
这就是我创造这一点的方式:
configLabel(offsetx,offsety,label){
labelStyle = new ol.style.Style({
text: new ol.style.Text({
font: '12px Calibri,sans-serif',
fill: new ol.style.Fill({ color: color }),
stroke: new ol.style.Stroke({
color: '#fff', width: 2
}),
text: label,
offsetY: offsety,
offsetX: offsetx
})
});
}
pointStyle = new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 25],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'img/point.ico'
})
});
var point = new ol.Feature(new ol.geom.Point(coord));
point.setStyle(pointStyle);
layerSource.addFeature(point);
var label1 = new ol.Feature(new ol.geom.Point(coord));
var style = configLabel(0,15, 'line1');
label1.setStyle(style);
layerSource.addFeature(label1);
var label2 = new ol.Feature(new ol.geom.Point(coord));
var style = configLabel(0,30, 'line2');
label2.setStyle(style);
layerSource.addFeature(label2);
var label3 = new ol.Feature(new ol.geom.Point(coord));
var style = configLabel(0,45, 'line3');
label3.setStyle(style);
layerSource.addFeature(label3);
var label4 = new ol.Feature(new ol.geom.Point(coord));
var style = configLabel(0,60, 'line4');
label4.setStyle(style);
layerSource.addFeature(label4);
非常感谢!
答案 0 :(得分:2)
我不知道有任何方法可以通过像素值而不是OpenLayers 3样式中的坐标值来绘制线条。但是,您可以使用style function,它将分辨率作为参数,并使用分辨率从所需的像素偏移中创建几何。
由于分辨率是以每个像素的地图单位数量提供的,因此从给定像素中查找位置是微不足道的:您将像素偏移量与分辨率相乘。
可以在下面的代码段中找到可运行的示例。
var feature = new ol.Feature(new ol.geom.Point([0, 0]));
var source = new ol.source.Vector({
features: [feature]
});
var fill = new ol.style.Fill({
color: 'rgba(255,255,255,1)'
});
var stroke = new ol.style.Stroke({
color: '#3399CC',
width: 1.25
});
var pointStyle = new ol.style.Style({
image: new ol.style.Circle({
fill: fill,
stroke: stroke,
radius: 5,
})
})
var lineLabelStyle = function(pointCoord, offsetX, offsetY, resolution, text) {
var labelCoord = [
pointCoord[0] + offsetX * resolution,
pointCoord[1] - offsetY * resolution,
];
return [
new ol.style.Style({
stroke: stroke,
geometry: new ol.geom.LineString([pointCoord, labelCoord])
}),
new ol.style.Style({
text: new ol.style.Text({
text: text,
textAlign: "left",
offsetY: offsetY,
offsetX: offsetX,
})
})
];
};
var styleFunction = function(feature, resolution) {
var pointCoord = feature.getGeometry().getCoordinates()
return [pointStyle].concat(
lineLabelStyle(pointCoord, 50, -10, resolution, "Label 1"),
lineLabelStyle(pointCoord, 50, 5, resolution, "Label 2"),
lineLabelStyle(pointCoord, 50, 20, resolution, "Label 3")
)
}
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Vector({
source: source,
style: styleFunction
})
],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
<link href="http://openlayers.org/en/v3.10.1/css/ol.css" rel="stylesheet" />
<script src="http://openlayers.org/en/v3.10.1/build/ol.js"></script>
<div id="map" class="map"></div>