只查询存在的点

Query the point only if it exist

我需要在单击该功能时看到 JSON 的信息。我的特征有很多点呈现为簇。使用下面的代码,我只能查询不在集群中的点:

map.on('singleclick', function(event) {
   const feature = map.forEachFeatureAtPixel(event.pixel, function(feature) {
    return feature
   })
    clusterSize = feature.get('features').length;
    if (clusterSize === 1) {
      if (feature) {
        json = feature.getProperties().features[0].values_;

        console.log(json);
      }
    }
})

当我点击地图的任何其他区域时,我看到错误:

Uncaught TypeError: feature is undefined

我的目标是做这样的伪代码:

if (feature != 0) { query point } else { do nothing }

我不清楚我该怎么做;我JavaScript的技能不强

feature.get('features') 是集群中特征的数组。要获取所有功能的属性,您需要将每个功能读入数组

json = [];
feature.get('features').forEach(function(feature){
  json.push(feature.getProperties());
});
console.log(json);

如果您的地图上既有集群特征又有普通特征,您将需要

   const feature = map.forEachFeatureAtPixel(event.pixel, function(feature) {
     return feature
   })
   if (feature) {
     const features = feature.get('features');
     if (features) {
       // this is a cluster
       ...
     } else {
       // not a cluster
       json = feature.getProperties()
     }
   }

我找到了一个解决方案:

map.on('singleclick', function(event) {
   const feature = map.forEachFeatureAtPixel(event.pixel, function(feature) {
    return feature
   })
   if (feature) {
     clusterSize = feature.get('features').length;
     if (clusterSize === 1) {
       json = feature.getProperties().features[0].values_;

       console.log(json);
     }
   }
})

现在,如果我单击未聚类的点,我可以获得属性,但如果我单击地图的其余部分,则不会出现错误。