javascript - 从获取的 WMS GetCapability 请求返回数组

标签 javascript arrays openlayers wms

我正在尝试从 WMS 图层返回时间值数组,我必须在 Openlayers 中填充下拉菜单。我已经能够在函数内的层中获取时间值列表(并将此输出打印到函数中的控制台),但无法从函数中获取此数组。当前代码如下:

var url = **working_WMS_url**

var GetCaps = new ol.format.WMSCapabilities();
fetch(url).then(function(response) {
      return response.text();
    }).then(function(text) {
      var result = GetCaps.read(text);
      var times = result.Capability.LayerLayer[0].Dimension;
      return times;
});
console.log(times);

// Section below links and populates dropdown menu
var time_list = document.getELementById("time_list");

for(var i = 0; i < times.length; i++) {
    var opt = times[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    time_list.appendChild(el);
}

为了确认下拉菜单正常工作,我使用手动定义的时间集进行了测试。我只是不明白为什么函数没有返回列表“times”。

为了清楚起见,我对 javascript 比较陌生,但一般不会编码,所以如果有一个非常简单的解决方案,我深表歉意。我花了最后一个小时浏览 StackOverflow 问题,但找不到准确回答此问题的问题。

最佳答案

fetch 是异步操作的,因此所有依赖于从 url 读取的文本的处理都应该在 fetch 的最后一个 then 子句中。

另一种选择(并非所有浏览器都支持)是声明异步调用函数并使用await 语句

async function myFunction(url, elementId) {

  var GetCaps = new ol.format.WMSCapabilities();
  var times = await fetch(url).then(function(response) {
      return response.text();
    }).then(function(text) {
      var result = GetCaps.read(text);
      console.log(result);
      var times = result.Capability.Layer.Layer[0].Dimension;
      return times;
  });
  console.log(times);

  // Section below links and populates dropdown menu
  var time_list = document.getElementById(elementId);

  for(var i = 0; i < times.length; i++) {
    var opt = times[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    time_list.appendChild(el);
  }
}

myFunction('working_WMS_url', 'time_list');

关于javascript - 从获取的 WMS GetCapability 请求返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57725048/

相关文章:

javascript - 未捕获的 TypeError : tplContent. importNode 不是函数

javascript - 使用函数返回数组的总和?我被困住了

javascript - 我如何使用 ng-repeat 迭代这个数组对象

javascript - OpenLayers 4 缩放到集群

openlayers - 创建 map 图例以匹配 OpenLayers.Style

javascript - 有没有办法在 OpenLayers 3 中禁用旋转?

javascript - 在通过 MyObject.prototype.method 和 'this' 变量定义的对象方法中使用 jQuery

javascript - chrome扩展程序应在youtube标签不清晰时暂停视频

java - 是否可以在接口(interface)中初始化数组?

python - 将数组四舍五入为另一个数组中给定的值