我刚刚开始使用OpenLayers 3,并且我尝试使用坐标动态更新“要素”几何属性,显然由于要素未移动,我错过了一些东西。到目前为止,这是我的上帝:

套接字

socket.on('mapData', function(mapData) {
    if (mapisloaded) {
            latLon = ol.proj.transform([mapData.lon, mapData.lat], 'EPSG:4326', 'EPSG:3857');
        // Initiate latlong object with mapData
        if (centerIsRequested) {

            //Center map with mapData
        };

        // Update marker with latlong from mapData
    };
});


基于Vector Icon Example的OpenLayers 3

var latLon = ol.proj.transform([10.904108, 59.788187], 'EPSG:4326', 'EPSG:3857');

var iconFeature = new ol.Feature({
    geometry: new ol.geom.Point(latLon),
    name: 'Null Island',
    population: 4000,
    rainfall: 500
});

var iconStyle = new ol.style.Style({
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        opacity: 0.75,
        src: 'imgs/lc.png'
    }))
});

iconFeature.setStyle(iconStyle);

var vectorSource = new ol.source.Vector({
    features: [iconFeature]
});

var vectorLayer = new ol.layer.Vector({
    source: vectorSource
});

var baseLayer = new ol.layer.Tile({
    source: new ol.source.OSM()
});

var view = new ol.View({
    center: latLon,
    zoom: 18,
});

var map = new ol.Map({
    target: 'map-canvas',
    layers: [ baseLayer, vectorLayer ],
    view: view
});


这些变化显然并没有改变,但是我知道魔术并不存在,只是放下一些东西就可以了。

我将如何完成这项简单的任务?我唯一想要的是在socket.io检测到新的mapdata(mapData.lat,mapData.lon)时更新其在地图上的位置的图标。

我试图深入研究不同的对象并在控制台和文档中读取它们的属性,并且我在此处在Stackoverflow上进行了搜索,但不幸的是没有运气。我是否应该加入iconFeature,还是必须以其他方式执行此操作?也许内置了一些真正简单的东西?任何帮助深表感谢。

最佳答案

如果要在地图上移动图标,最好为此使用ol.Overlay。您可以在每个更改上使用marker.setPosition(coord)

A working fiddle。单击地图以更改标记的位置。

09-20 22:47