Drawing on a Google Map using pixel space

Most things on Google Maps require you to use latitude and longitude, which can make things a little tricky when trying to draw on the map. There is a great little class buried in the v3 API that makes this pretty easy though.

The MapCanvasProjection class, while difficult to get at, allows you to draw on a map using pixel space coordinates rather than latitude and longitude. Take a look at the dashed line below. It was drawn using the divs height and width in pixels.

this is the map

The object is made available to the OverlayView from within the draw method, make it a little tough to get at. Use the following code to obtain a reference to the MapCanvasProjection class:

overlay = new google.maps.OverlayView();
overlay.draw = function() {};
mapCanvasProjection = overlay.getProjection();

Once you have the reference, things become much easier!

convertPixels = function(x, y) {
 return mapCanvasProject.fromDivPixelToLatLng(new google.maps.Point(x, y));

top = 0;
middle = $('#mapcanvas').width() / 2;
bottom = $('#mapcanvas').height();

aLines = [convertPixels(middle, top), convertPixels(middle, bottom)];

polyline = new google.maps.Polyline({
 path: aLines,
 strokeOpacity: 1,
 strokeWeight: 1,
 map: map

You can download a working version of the example.