Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps v3 OverlayView.getProjection()

I cannot seem to figure out why the object returned by getProjection() is undefined. Here is my code:

 // 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);

My error is: Cannot call method 'fromLatLngToContainerPixel' of undefined

like image 503
Arlo Carreon Avatar asked Sep 14 '10 16:09

Arlo Carreon


1 Answers

Actually, i the reason why this happens is because the projection object is created after the map is idle after panning / zooming. So, a better solution is to listen on the idle event of the google.maps.Map object, and get a reference to the projection there:

// 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();
})
like image 154
Mihai Tomescu Avatar answered Sep 28 '22 06:09

Mihai Tomescu