views:

159

answers:

1

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

A: 

I kind of figured out what was going on. Even though it is still not crystal clear why this happens, I know that I had to instantiate the variable "overlay" right after instantiating my google map (HAR.map). So I practically moved that code snippet into my HAR class and now i use:

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

So now, every time I create a map via my class "HAR" I also have a parallel OverlayView object within my class.

The Error could have been with losing scope of my class object, but I think it was more of the map event "projection_changed" not being fired. I got a hint from the map API docs for map class, under method 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."

If you are getting the similar issue, make sure that you assign your overlayView.setMAP( YOUR_MAP_OBJECT ) closely after instantiating the map object.

Arlo Carreon