OpenLayers 5-有没有一种方法可以使群集文本居中?

时间:2019-02-06 07:39:38

标签: openlayers openlayers-5

我正在制作一个显示我的标记的应用程序,并且因为有很多标记,我需要制作群集。除文本外,其他所有内容均按预期工作。

我尝试过更改anchor和anchor [X / Y] Unit,但是即使将其更改为固定像素,它也始终会显示错误。

这是我的代码:

const style = new Style({
    image: new CircleStyle({
        radius: 12,
        stroke: new Stroke({
            color: '#ffffff',
            width: 1,
        }),
        fill: new Fill({
            color: '#3399CC'
        }),
        anchorXUnits: 'fraction',
        anchorYUnits: 'fraction',
        anchor: [0.5, 0.5],
    }),
    text: new Text({
        font: '14px/24px sans-serif',
        text: '2',
        fill: new Fill({
            color: '#ffffff'
        })
    })
});

var clusters = new VectorLayer({
    source: clusterSource,
    style: style
});

群集中的文本未正确对齐。我附上一些图片以进一步说明问题。

not aligning cluster texts not aligning cluster texts

2 个答案:

答案 0 :(得分:2)

我认为没有办法单独使用OpenLayers API使其正确对齐。我想出了另一种解决方案。我做了一个在Canvas Context中渲染圆和文本的函数。

我使用此功能:

const createImage = function (diameter, text) {
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');

    // set canvas width and height to double the outer diameter
    canvas.width = diameter * 2;
    canvas.height = diameter * 2;

    // white border
    ctx.beginPath();
    ctx.arc(diameter, diameter, diameter, 0, 2 * Math.PI);
    ctx.fillStyle = '#ffffff';
    ctx.fill();

    // inner circle
    ctx.beginPath();
    ctx.arc(diameter, diameter, diameter - 1.5, 0, 2 * Math.PI); // the -1.5 makes a nice offset
    ctx.fillStyle = '#104ddb';
    ctx.fill();

    // text in the circle
    ctx.beginPath();
    ctx.font = '14px Arial';
    ctx.fillStyle = '#ffffff';
    ctx.textAlign = 'center'; // center horizontally
    ctx.textBaseline = 'middle'; // center vertically
    ctx.fillText(text, diameter, diameter);

    return canvas.toDataURL();
};

样式如下:

style = new Style({
    image: new Icon({
        src: createImage(24, '2'), // createImage(radius, text)
        imgSize: [24, 24],
    }),
});

我希望它能对某人有所帮助。

答案 1 :(得分:0)

检查有关地震群的示例。所有文本对齐似乎都可以。

https://openlayers.org/en/latest/examples/earthquake-clusters.html

相关问题