【问题标题】:Openlayers 3 Add Movable Marker with Icon and TextOpenlayers 3 添加带有图标和文本的可移动标记
【发布时间】:2014-10-23 00:57:32
【问题描述】:

在 OL3 中,我成功地制作了一张带有可移动标记的地图:

var mapVectorSource = new ol.source.Vector({
    features: []
});
var mapVectorLayer = new ol.layer.Vector({
    source: mapVectorSource
});
map.addLayer(mapVectorLayer);

function makeMovable(feature) {
    var modify = new ol.interaction.Modify({
        features: new ol.Collection([feature])
    });

    feature.on('change',function() {
        console.log('Feature Moved To:' + this.getGeometry().getCoordinates());
    }, feature);
    return modify;
}

function createMarker(location, style){
    var iconFeature = new ol.Feature({
        geometry: new ol.geom.Point(location)
    });
    iconFeature.setStyle(style);

    return iconFeature
}

iconStyle = new ol.style.Style({
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
        anchor: [0.5, 1],
        anchorXUnits: 'fraction',
        anchorYUnits: 'fraction',
        src: '/static/img/marker-icon.png',
    }))
});
var marker = createMarker(ol.proj.transform([38, 50], 'EPSG:4326', 'EPSG:3857'), iconStyle);
mapVectorSource.addFeature(marker);
var modifyInteraction = makeMovable(marker);
map.addInteraction(modifyInteraction);

但我想添加 >10 个标记,所以我需要用数字或文本标记它们。有什么方法可以将文本添加到叠加层?如果我检查iconStyle,我发现它有一个getText() 函数,但该函数总是只返回undefined,并且没有伴随的setText() 函数。像这样定义它似乎也很自然:

iconStyle = new ol.style.Style({
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
        anchor: [0.5, 1],
        anchorXUnits: 'fraction',
        anchorYUnits: 'fraction',
        src: '/static/img/marker-icon.png',
    })),
    text: "Hello, Marker"    // <- operative line
});

但这似乎是不允许的。另一个自然的选择可能是将 html 元素附加到样式中,以便我们可以渲染任何我们想要的东西,但似乎没有办法做到这一点。

那么,如何创建一个带有文本标签的标记?

【问题讨论】:

    标签: javascript openlayers gis openlayers-3


    【解决方案1】:

    如this 示例中所见,解决方案是使用样式列表而不是单个样式。

    在这种情况下很简单:

    iconStyle = [
        new ol.style.Style({
            image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
                anchor: [0.5, 1],
                anchorXUnits: 'fraction',
                anchorYUnits: 'fraction',
                src: '/static/img/marker-icon.png',
            }))
        }),
        new ol.style.Style({
            text: new ol.style.Text({
                text: "Wow such label",
                offsetY: -25,
                fill: new ol.style.Fill({
                    color: '#fff'
                })
            })
        })
    ];
    

    【讨论】:

    • 为我节省了一天
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多