[GIS] OpenLayers 4 popup

javascriptopenlayers

I'm trying to create a popup when I click on a feature layer (the position is the mouse cursor) but I want this option just on the feature layer and not in the whole map.
How can I stop to create a popup when the click is on the map and not in that layer?

Here my code:

... 

var pixel;
var hit;

map.on('singleclick', function(evt) {
  document.getElementById('popup-content').innerHTML = '';
  var viewResolution = map.getView().getResolution();
  var coordinate = evt.coordinate;
  var url = infosource.getGetFeatureInfoUrl(
    evt.coordinate, viewResolution, projection, {'INFO_FORMAT': 'text/html'});
  if (url) {
    var parser = new DOMParser();
    var xmlDoc = parser.parseFromString(url,"text/xml");
    console.log(fullInfo(xmlDoc));
    document.getElementById('popup-content').innerHTML = xmlDoc;
  }
  if(hit){
    overlay.setPosition(coordinate);
  } else {
    overlay.setPosition(undefined);
  }
});

map.on('pointermove', function(evt) {
  if (evt.dragging) {
    return;
  }
  pixel = map.getEventPixel(evt.originalEvent);
  hit = map.forEachLayerAtPixel(pixel, function() {
    return true;
},null, function(layer) {
      return layer === pmfeatlayer;
    });
  map.getTargetElement().style.cursor = hit ? 'pointer' : '';
});


} // END MAP INIT

var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');

closer.onclick = function() {
  overlay.setPosition(undefined);
  closer.blur();
  return false;
};

here the examples I'm using:

https://openlayers.org/en/latest/examples/popup.html?q=coordin

https://openlayers.org/en/latest/examples/getfeatureinfo-tile.html

UPDATE

Has to be compatible with mobile.

Best Answer

It seems that some solutions I tried don't work on mobile so, instead of using the layer I based my approach on the content I have back from the request and not the layer itself.

if (url) {

var xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.send();
xhttp.onreadystatechange = function (aEvt) {
  if (xhttp.readyState == 4) {
    if (xhttp.status == 200)  {
      //console.log(xhttp);
      document.getElementById('popup-content').innerHTML = xhttp.responseText;
      //fullInfo(xhttp.responseText);

      // set the position of the popup on the screen
      var parser = new window.DOMParser();
      var res = parser.parseFromString(xhttp.responseText, "text/xml");
      if(res.getElementsByTagName('item').length != 0){
        overlay.setPosition(coordinate);
      } else {
        overlay.setPosition(undefined);
      }

    } 
  }
};
}