Search code examples
javascriptjqueryfunctiononclicklisteneropenlayers-3

Remove 'singleclick' map event if div is closed in OpenLayers 3


I have a button on an OpenLayers 3 web map that when clicked activates a function that returns Google Street Views images in a div when the user clicks on the map.

This is working fine, but what I would like to do is disable this on map click function when the div is closed.

At the moment I have:

$("#street-view").click(function() {
  map.on('singleclick', function(evt) {
    var coord = evt.coordinate;
    var x = coord[0];
    var y = coord[1];
    var os1w = new OSRef(x, y);
    var coordres = os1w.toLatLng(os1w);
    coordres.OSGB36ToWGS84();
    xResult = coordres.toLatString();
    yResult = coordres.toLngString();
    var sv = new google.maps.StreetViewService();
    panorama = new google.maps.StreetViewPanorama(document.getElementById('street-view-image'));
    var googleCoord = new google.maps.LatLng(xResult,yResult);
    sv.getPanorama({location: googleCoord, radius: 20}, getStreetViewImage);
  });
});

function getStreetViewImage(data, status) {
  if (status === google.maps.StreetViewStatus.OK) {
    panorama.setPano(data.location.pano);
    panorama.setPov({
      heading: 0,
      pitch: 0
    });
    $('#street-view-pane').fadeIn("slow");
    panorama.setVisible(true);
  } else {
    $("#street-view-image").html("Sorry! No Street View images are available at this location.");
  }
}


$("#close-street-view").click(function(evt) {
  $('#street-view-pane').fadeOut("slow");
});

I have tried creating an if statement inside a for loop to say if the loop is more than 0 and the div is open, then run the code (so if the div isn't showing then do nothing) - but this doesn't work.

Is there a simple way to stop the singleclick event once the div is closed? I have a singleclick event that identifies features on the map which is enabled on the page load so I cannot disable all singleclick functions.

Thanks


Solution

  • The on method of ol.Map returns a unique key for that event listener. If you want to be able to cancel the event listener, save that key and use it with the unByKey method.