【问题标题】:Google Maps v3 OverlayView.getProjection()谷歌地图 v3 OverlayView.getProjection()
【发布时间】:2010-09-14 16:12:56
【问题描述】:

我似乎无法弄清楚为什么 getProjection() 返回的对象是未定义的。这是我的代码:

 // Handles the completion of the rectangle
  var ne = recBounds.getNorthEast();
  var sw = recBounds.getSouthWest();
  $("#map_tools_selat").attr( 'value', sw.lat() );
  $("#map_tools_nwlat").attr( 'value', ne.lat() );
  $("#map_tools_selng").attr( 'value', ne.lng() );
  $("#map_tools_nwlng").attr( 'value', sw.lng() );

  // Set Zoom Level
  $("#map_tools_zoomlevel").attr( 'value', HAR.map.getZoom()+1 );
  document.getElementById("map_tools_centerLat").value = HAR.map.getCenter().lat();
  document.getElementById("map_tools_centerLong").value = HAR.map.getCenter().lng(); 

  // All this junk below is for getting pixel coordinates for a lat/lng  =/
  MyOverlay.prototype = new google.maps.OverlayView();
  MyOverlay.prototype.onAdd = function() { }
  MyOverlay.prototype.onRemove = function() { }
  MyOverlay.prototype.draw = function() { }
  function MyOverlay(map) { this.setMap(map); }
  var overlay = new MyOverlay(HAR.map);
  var projection = overlay.getProjection();
  // END - all the junk
  var p = projection.fromLatLngToContainerPixel(recBounds.getCenter());
  alert(p.x+", "+p.y);

我的错误是:Cannot call method 'fromLatLngToContainerPixel' of undefined

【问题讨论】:

  • 顺便说一句:我粘贴了 jquery 部分以显示我的地图对象 (HAR.map) 确实有效。我已经多次确认 getCenter() 和 getZoom() 函数实际上返回了正确的值。所以 HAR.map 对象是合法的。

标签: google-maps google-maps-api-3


【解决方案1】:

其实,我之所以会出现这种情况,是因为投影对象是在地图平移/缩放后空闲后创建的。因此,更好的解决方案是监听 google.maps.Map 对象的 idle 事件,并获取对那里的投影的引用:

// Create your map and overlay
var map;
MyOverlay.prototype = new google.maps.OverlayView();
MyOverlay.prototype.onAdd = function() { }
MyOverlay.prototype.onRemove = function() { }
MyOverlay.prototype.draw = function() { }
function MyOverlay(map) { this.setMap(map); }

var overlay = new MyOverlay(map);
var projection;

// Wait for idle map
google.maps.event.addListener(map, 'idle', function() {
   // Get projection
   projection = overlay.getProjection();
})

【讨论】:

  • 太棒了!我需要试试这个。
【解决方案2】:

我有点明白发生了什么。尽管仍然不清楚为什么会发生这种情况,但我知道我必须在实例化我的谷歌地图(HAR.map)之后立即实例化变量“overlay”。所以我实际上将代码 sn-p 移到了我的 HAR 类中,现在我使用:

HAR.canvassOverlay.getProjection().fromLatLngToContainerPixel( recBounds.getCenter() );

所以现在,每次我通过我的类“HAR”创建地图时,我的类中也有一个并行的 OverlayView 对象。

错误可能是我的类对象的范围丢失,但我认为更多的是地图事件“projection_changed”没有被触发。我从地图类的地图 API 文档中得到了一个提示,在 getProjection() 方法下:

Returns the current Projection. If the map is not yet initialized (i.e. the mapType is still null) then the result is null. Listen to projection_changed and check its value to ensure it is not null.

如果您遇到类似问题,请确保在实例化地图对象后密切分配您的 overlayView.setMAP(YOUR_MAP_OBJECT)。

【讨论】:

  • 我也有这个问题,是因为我根本没有this.setMap()。谢谢。
猜你喜欢
  • 2018-10-19
  • 1970-01-01
  • 1970-01-01
  • 2012-08-03
  • 2013-05-03
  • 2014-04-05
  • 2014-04-06
  • 2011-07-14
  • 1970-01-01
相关资源
最近更新 更多