javascript - 更新openlayers 3中特征的坐标

标签 javascript openlayers-3

我有一个 javascript 模型,它具有纬度和经度值。我必须通过元素的 ID 在 map 上找到一个特征并更新它的位置和其他几个属性。我的代码如下所示:

function updateCoordinate(item) {
    var features = source.getFeatures();
    var featureToUpdate;

    // find feature by custom property
    for(var i=0; i< features.length; i++) {
       if (features[i].get('ID') == item.ID) {
           featureToUpdate = features[i];
           break;
       }
    } 

    // get lon, lat from input item
    var lon  = item.Coordinate.Longitude;
    var lat  = item.Coordinate.Latitude;

    // update geometry (not working)
    featureToUpdate.set('Geometry', new ol.geom.Point(getPointFromLongLat(lon, lat)));
    // update custom properties (working)
    featureToUpdate.set('MapMarkerTitle', item.Title);
    // ...
}

function getPointFromLongLat (long, lat) {
    return ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857')
}

我做错了什么吗?有更好的方法吗?有没有更好的方法来通过自定义属性查找特征?

我所说的自定义属性是指该功能是这样启动的:

var fea = new ol.Feature({
            geometry: new ol.geom.Point(getPointFromLongLat(lon, lat)),
            MapMarkerTitle : 'AAA',
            // ...
         }) 
source.addFeatures([fea]);

自定义属性正在更新,但坐标似乎没有更新。更新位置后是否会重新绘制特征?然而,标签被重新绘制,所以我认为是的。

更新

经过一些调试后我发现,我将“geometry”属性拼错为大写字母。 实际上:

featureToUpdate.set('geometry', new ol.geom.Point(getPointFromLongLat(lon, lat)));

设置新位置并立即更新位置。我仍然想知道我正在做的是好方法还是更好。谢谢!

最佳答案

您可以将其简化为:

function updateCoordinate(item) {
    var featureToUpdate = source.getFeatureById(item.ID);

    var coord = getPointFromLongLat(item.Coordinate.Longitude, item.Coordinate.Latitude);

    featureToUpdate.getGeometry().setCoordinates(coord);
    featureToUpdate.set('MapMarkerTitle', item.Title);
}

关于javascript - 更新openlayers 3中特征的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32089959/

相关文章:

angularjs - 在 openlayer Angular 指令缩放按钮不显示

javascript - 使用 Openlayers 3 在 map 图 block 上绘制多边形,其中使用自定义图 block 服务器

javascript - Openlayers3 : How to add a colored border around a marker icon?

javascript - 如何通过拖放上传多个文件并使用ajax浏览

javascript - 如何响应某个区域外的点击?

javascript - jQuery 图片滑动插件

javascript - 如何在本地保存 map 值以供用户第二次访问

javascript - 如何在 Amazon.com 上的顶级广告上放置 div

javascript - 有条件地在javascript代码中隐藏一段json

移动设备上的 OpenLayers 3 dragBox