Javascript – Pixel distance in Google Map (API V3) to avoid overlapping labels / overlays

google mapsgoogle-maps-api-3javascript

What is the best way to calculate the pixel distance between to coordinates (lat/lon) in a Google Map. I am not asking about the distance in km/miles (therefore I have a library), but pixels on the screen considering the current zoom factor.

Background: I want to draw overlays without overlapping them. So I need to calculate the offset for these positions. So in a lower zoom factor a distance of 500 km can mean the overlays do overlap, while at 50km they don't.

Of course, any other algorithm to avoid overlaps not based on the pixel distance would be appreciated.

— Update —

Guess is is going in the direction of clustering, will check this:

  1. http://www.appelsiini.net/2008/11/introduction-to-marker-clustering-with-google-maps
  2. http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/1.0/examples/advanced_example.html

— Update —

Most likely I can use this here: http://code.google.com/apis/maps/documentation/javascript/reference.html

google.maps.MapCanvasProjection.fromLatLngToDivPixel

To get the projection I will use the answers here:

  1. Pan point on Google Map to specific pixel position on screen (API v3)
  2. How to call fromLatLngToDivPixel in Google Maps API V3?

Best Answer

First I found that what I am looking for is subject of the clustering libraries / examples:

  1. http://www.appelsiini.net/2008/11/introduction-to-marker-clustering-with-google-maps
  2. http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/1.0/examples/advanced_example.html

The examples showed me a method google.maps.MapCanvasProjection.fromLatLngToDivPixel, which required a projection of the map. Eventually the following topics revealed how to get this projection:

  1. Pan point on Google Map to specific pixel position on screen (API v3)
  2. How to call fromLatLngToDivPixel in Google Maps API V3?