janr
janr

Reputation: 3694

OpenLayers map event cannot call method

I want to react on Openlayers map events, but I have a problem to call a class method when the event got emitted. The relevant code-snippet looks as follows:

function OpenLayersMap(divname) {
  var osmLayer = new OpenLayers.Layer.OSM("Open Street Maps");
  var gmLayer = new OpenLayers.Layer.Google("Google Maps");

  this.proj = new OpenLayers.Projection("EPSG:4326");
  this.map = new OpenLayers.Map(
  {
    div: divname,
    allOverlays: false,
    theme: null,
    controls: 
    [
      new OpenLayers.Control.Attribution(),
      new OpenLayers.Control.Navigation(),
      new OpenLayers.Control.LayerSwitcher(),
      new OpenLayers.Control.PanZoomBar(),
      new OpenLayers.Control.ScaleLine(),
      new OpenLayers.Control.MousePosition(
        {
          displayProjection: this.proj
        }
      ),
      new OpenLayers.Control.KeyboardDefaults()
    ],
    eventListeners: 
    {
      'moveend' : this.moved,
      'zoomend' : this.zoomed
    }
  }
  );
  this.map.addLayers([osmLayer, gmLayer]);
  this.map.setCenter(new OpenLayers.LonLat(8.56, 50).transform(
    this.proj, 
    this.map.getProjectionObject()), 
    10
  );
  this.updateMapData();
}

OpenLayersMap.prototype = {
  constructor : OpenLayersMap,

  updateMapData : function() {
    console.log("updateMapData!!!!!!!!");
    // Some more stuff
  },

  moved : function(event) {
    console.log("Map has been moved!");
    this.updateMapData(); // Line 94
  },

  zoomed : function(event) {
    console.log("Zoom has been used!");
    this.updateMapData();
  }
}

The firebug output after loading the page:

Map has been moved!
Uncaught Type error: Object #<Object> has no method 'updateMapData'
Map has been moved!
Uncaught Type error: Object #<Object> has no method 'updateMapData'
   OpenLayersMap.moved (ol.js:94)
   OpenLayers.Events.OpenLayers.Class.triggerEvent (OpenLayers-2.11-min.js:400)
   OpenLayers.Map.OpenLayers.Class.moveTo (OpenLayers-2.11-min.js:499)
   OpenLayers.Map.OpenLayers.Class.setCenter (OpenLayers-2.11-min.js:473)
   OpenLayers.Map.OpenLayers.Class.updateSize (OpenLayers-2.11-min.js:464)
   (anonymous function) (OpenLayers-2.11-min.js:158)

So the moved method is invoked, but not the updateMapData method. If I remove the eventListeners part, the updateMapData call at the constructor end succeeds!

Can anybody tell me why the method cannot be called?

Thanks in advance!

Upvotes: 1

Views: 2468

Answers (1)

janr
janr

Reputation: 3694

I found a solution for my problem, but I do not entirely understand what the problem was. So feel free to comment my solution or maybe answer with a better one.

var self = this;
//...
eventListeners: 
{
  'moveend' : function(event) { self.moved(event); },
  'zoomend' : function(event) { self.zoomed(event); }
}
//...

I suspect that when the object is created the prototype methods (e.g. moved) of OpenLayersMap aren't known.

Upvotes: 1

Related Questions