Adrian Thompson Phillips
Adrian Thompson Phillips

Reputation: 7141

map.on('click') coordinates wrong in Firefox

I am using OpenLayers 3.10.1 and the following code:

map.on('click', function (map, evt) {
    var mouseCoords = [evt.originalEvent.offsetX, evt.originalEvent.offsetY];

    alert(mouseCoords);
});

When I click as near as I can to the upper left corner of the map in IE or Chrome, I get an alert with the mouse coordinates offset from the top left corner of the map div, i.e. something sensible like [3,4].

But when I try the same things I get the mouse coordinates relative to the browser window and not the map div. Does anyone know why this is? Am I using an outdated way to find the mouse coordinates (ultimately so I can calculate which feature was clicked)?

Upvotes: 4

Views: 7461

Answers (2)

boly38
boly38

Reputation: 1955

The following code works for me (openlayer 4.4, angular 4+)

_initMap() {
  console.info("_initMap");
  this.mapW = new ol.Map({
      layers: [
        new ol.layer.Tile({
          source: new ol.source.OSM()
        })
      ],
      target: 'myMapDiv',
      controls: ol.control.defaults({
          attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
            collapsible: false
          })
      }),
      view: new ol.View({
          center: ol.proj.fromLonLat([this.lon, this.lat]);,
          zoom: 12
      })
    });
  const theMap = this.mapW; 
  // display on click
  this.mapW.on('click', function(evt) {
    /* // you want to detect feature click
    var feature = theMap.forEachFeatureAtPixel(evt.pixel,
        function(feature, layer) {
          return feature;
        });
    if (feature) {
      var fname = feature.getProperties().name;
      console.info("feature clicked:" + fname);
      return;
    }
    */
    console.info(evt.coordinate);
    console.info(ol.proj.toLonLat(evt.coordinate)); //   <=== coordinate projection
  });

JS console results (when clicking close to Grenoble in France):

(2) [637000.3050167585, 5652336.68427412]
(2) [5.722271099853512, 45.19540527485873]

Upvotes: 1

Jonatas Walker
Jonatas Walker

Reputation: 14150

Some alternatives:

map.on('click', function(evt){
    console.info(evt.pixel);
    console.info(map.getPixelFromCoordinate(evt.coordinate));
});

Upvotes: 4

Related Questions