簡體   English   中英

Openlayers 3添加帶圖標和文字的可移動標記

[英]Openlayers 3 Add Movable Marker with Icon and Text

在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元素附加到樣式,以便我們可以渲染任何我們想要的東西,但似乎沒有辦法做到這一點。

那么,如何創建具有文本標簽的標記?

例所示,解決方案是使用樣式列表而不是單個樣式。

在這種情況下,它非常簡單:

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'
            })
        })
    })
];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM