1

我有 JavaScript 语言的代码,当我输入 console.log(event) 时,输出是:

{"type":"FeatureCollection","features":[{"type":"Feature","id":"","geometry":null,"properties":{"GRAY_INDEX":176}}],"totalFeatures":"unknown","numberReturned":1,"timeStamp":"2021-03-03T14:04:13.362Z","crs":null}

我想要“属性”部分中的“GRAY_INDEX”值。我应该怎么办?这是我的代码:

map.on('singleclick', function(evt) {
    document.getElementById('info').innerHTML = '';
    var view = map.getView();
    var viewResolution = view.getResolution();
    var url = UnTiled.getSource().getFeatureInfoUrl(
        evt['coordinate'],
        viewResolution,
        'EPSG:3857', 
        {'INFO_FORMAT': 'application/json'}
      );
      console.log(url);
      if (url) {
        fetch(url)
          .then(function (response) { return response.text(); })
          .then(function (html) {
            html;
            console.log(html);
          });
      }
      
     });

我试过了 :

console.log(html["properties"]

但控制台说未定义

4

2 回答 2

0

似乎您在参数“html”中获得了 JavaScript 对象的 JSON 表示,如果是这种情况,您首先需要将 JSON 解析为对象。比您想要访问功能的属性。Features 是一个数组,所以如果你想获取所有元素的属性,你应该这样做:

var html = '{"type":"FeatureCollection","features":[{"type":"Feature","id":"","geometry":null,"properties":{"GRAY_INDEX":176}}],"totalFeatures":"unknown","numberReturned":1,"timeStamp":"2021-03-03T14:04:13.362Z","crs":null}';
var o = JSON.parse(html);
o.features.forEach(function(each, index) { 
  console.log(`index = ${index}\n`,each.properties);
});

于 2021-03-03T14:43:29.423 回答
0

如果您格式化了 json,您将能够更清楚地看到如何访问它:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "id": "",
      "geometry": null,
      "properties": {
        "GRAY_INDEX": 176
      }
    }
  ],
  "totalFeatures": "unknown",
  "numberReturned": 1,
  "timeStamp": "2021-03-03T14:04:13.362Z",
  "crs": null
}

如果将上述内容分配给html,那么要访问该GRAY_INDEX值,您可以:

html.features[0].properties.GRAY_INDEX

您需要先将响应解析为 JSON,方法是使用response.json()代替response.text()或添加html = JSON.parse(html),然后再尝试访问它。

于 2021-03-03T14:41:13.933 回答