I'm trying to teach myself OpenLayers and took an introductory course in which we received the whole code. For my first own project I want to do something similar and recycle some of the code. But there is some part of the code I don't understand and hope that someone can explain it to me. The idea is that the user can click on the vector element on the map (schools in this case) and recive information about its attributes. Here is the code:

map.on('singleclick', function(e) {
  var feature = map.forEachFeatureAtPixel(e.pixel, function(feature) {
    return feature;

  var schoolName = feature ? feature.get('name') : '';

All right, when the user clicks on the map, it fires the function e. In this function we create a variable with the name feature and this variable recieves the function forEachFeatureAtPixel, which returns the variable feature. Thus, the way I understand it the value of the variable feature is itself. Thus, it shouldn't have a value. Where is my logic mistake?

Furthermore I don't understand the next line either. We create a variable schoolName and this variable gets the value "feature ? feature.get('name') : ' ';

But what does the "?" do and why do we need : ' ';

Can someone explain these lines of code?


The function forEachFeatureAtPixel gets two parameters: the clicked pixel and the function that will be called when a feature is found. This function 1st argument must be called feature (see the doc for a few other possible values)

It is a different scope than the variable that you have defined, so despite their name, they do not share the same content. Inside the callback function, the code returns the feature that is now assigned to the variable you have defined.

It might be easier to understand using

 var clicked_feature = map.forEachFeatureAtPixel(e.pixel, function(feature) {
    return feature;

For var schoolName = feature ? feature.get('name') : '';, it a way of writing an if/else statement. It means:

IF feature has a value,

THEN read the value of its attribute name and save in the variable schoolName.

ELSE, save an empty string in schoolName.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.