Search code examples
javascriptopenlayers

Query the point only if it exist


I need to see the information as JSON when I click on the feature. My features are many point rendered as cluster. With the code below I can query the point only if it is not into a cluster:

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);
      }
    }
})

When I click on any other area of my map I see thi error:

Uncaught TypeError: feature is undefined

My aim is do something like this pseudo-code:

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

For me is not clear how I can do this; my JavaScript's skills aren't strong


Solution

  • I found one solution:

    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);
         }
       }
    })
    

    Now if I click on the unclustered point I can get the properties, but if I click on the rest of the map there aren't errors.