首页 > 解决方案 > 使用函数更改 openlayers 中可见的图标颜色

问题描述

我试图做到这一点,我将能够更改标记图标的颜色,使其在地图中可见。它们在地图中以不同的颜色显示。这些颜色对应于 json cat_id 键。

1: "http://dev.openlayers.org/img/marker.png",
2: "http://dev.openlayers.org/img/marker-blue.png",
3: "http://dev.openlayers.org/img/marker-gold.png",
4: "http://dev.openlayers.org/img/marker-green.png",

地图中的每个标记图标都从脚本标签中数据 id 中的 json 对象获取其位置、颜色和其他有价值的数据。我没有编写与 openlayer 库接近的那部分工作的代码。我写了整个脚本的以下部分:

var json = document.getElementById('data').innerHTML;
json = JSON.parse(json); // converts text into JSON

// search criteria (could be changed)
var $search_postal = "8912JB";
var $search_number = "10";
var $change_cat = 1;

function changeColor() {
    for (var key in json) {
        if (json.hasOwnProperty(key)) {
            if (json[key].postal == $search_postal) {
                if (json[key].number == $search_number) {
                    alert("Gonna change cat_id " + json[key].cat_id + " of the number search string " + $search_number + " of the postal search string " + $search_postal + " to cat_id " + $change_cat);
                    json[key].cat_id = "1";
                    alert('Changed!');
                    const posts = json; // the constant that is used to display the icons
                    var myJSON = json;
                    document.getElementById('demo').innerHTML = JSON.stringify(myJSON, undefined, 2); // changes of the json data to see on screen
                }
            }
        }
    }
}

const posts = json; //the constant that is used to display the icons

var myJSON = JSON.stringify(json);
document.getElementById('demo').innerHTML = myJSON;

此脚本将更改给定搜索输入的 cat_id。在示例中,它会搜索编号为 1 的邮政 8912JB。一旦它完成循环以找到它的位置,它会将 cat_id 的值 3 更改为 1。换句话说,json 数据已更改。由于它存储在 const 帖子中,因此我将这个缺点替换为更改的数据。我的问题是我无法使用已更改的新 json 数据刷新地图中的标记图标(cat_id:邮政 8912JB 编号 10 的 1)。这与对 openlayers 和 Javascript 的知识较少有关。我已经为此苦苦挣扎了两周。有人可以帮我完成这个吗?如果它从颜色改变是唯一需要的。我只需要对变量 $search_postal、$search_number 和 $change_cat 进行更改。

这是调试页面:https ://jsfiddle.net/j4z1vpht/4/

谢谢你的帮助,

网格

标签: javascriptjquerymapsopenlayers

解决方案


您需要将新类别更新为地图功能,如下所示:

const updateFeatureCategory = (featureId, categoryId) => {
  const feature = marker_layer.getSource().getFeatureById(featureId);
  const post = feature.get("post");
  const updatedPost = {
    ...post,
    cat_id: categoryId
  }
  feature.set("post", updatedPost);
}
function changeColor() {
  ...
  json[key].cat_id = "1";
  updateFeatureCategory(key, "1");
  ...
}

这是一个工作小提琴:https ://jsfiddle.net/wsm2h3qz/1/


推荐阅读