Convert lat, lng and zoom values to pixel (x,y) on a map
March 6th, 2009 by Carlos BarrosWorking on a project this week, that involves Google Maps, I needed to, given a latitude, a longitude and a zoom level, calculate the pixel position (x,y) within the map. If you need to do this using javascript, it’s pretty easy, as GMap API provides a handy method to do this:
var pixel = map.getCurrentMapType().getProjection().fromLatLngToPixel(new GLatLng(10,20),map.getZoom());
Unfortunately, my need was to convert lat, lng and zoom into pixel position from PHP. I “googled” about this subject for a while, and it’s incredible how frequent this need is, and how this information lacks. I saw a lot of people asking for similar things, and also some people that claim that got it working, but without providing any code for this. Googling a bit more I figured out that google uses one thing called Mercator Projection, but even this being a standard, I didn’t find anything that does what I needed. After a lot of time searching about this, I finally stumbled upon a perl script with a set of methods that accomplishes the task. Actually, this perl script is more focused on working with map “tiles”, but there are two methods that does exactly what I needed. It was just a matter of converting these perl methods into php and we’re done.



