OpenLayers地图事件无法调用方法

时间:2012-10-18 07:01:28

标签: javascript openlayers

我想对Openlayers地图事件做出反应,但是在发出事件时调用类方法时遇到问题。相关的代码片段如下所示:

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();
  }
}

加载页面后的firebug输出:

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)

因此调用移动的方法,但不调用updateMapData方法。如果我删除 eventListeners 部分,构造函数结束时的updateMapData调用会成功!

有人可以告诉我为什么不能调用该方法吗?

提前致谢!

1 个答案:

答案 0 :(得分:1)

我找到了解决问题的方法,但我并不完全明白问题所在。所以请随意评论我的解决方案,或者回答一个更好的解决方案。

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

我怀疑在创建对象时,OpenLayersMap的原型方法(例如移动)是未知的。