How Many Miles are in a Pixel?

Darya Slobodyanik
Hackmamba
Published in
2 min readJan 31, 2018

Say you want to show a particular area of the Earth on your website using Google Maps. You’ve got a specific 500px × 500px spot carved out for it and you want to make sure you capture the entire area — all you need to do is figure out how to scale miles to pixels.

It seems like a simple enough problem, but there’s one complication: we’re trying to display a round object on a flat surface. The Mercator projection, which Google Maps uses, becomes more and more distorted the farther you travel from the equator. In other words, all else being equal, our little 500px map will show a different square footage depending on what latitude we’re centered on.

So, how do we zoom to the right scale while accounting this distortion? A tenacious search of Google Groups forums eventually yields this answer from a Google employee:

meters/px = 156543.03392 * Math.cos(latitude * Math.PI / 180) / Math.pow(2, zoom)

We just need to transform the equation so we’re solving for zoom.

zoom = Math.log2(156543.03392m/px * Math.cos(latitude * Math.PI / 180) * pixels / meters)

In the Google Maps API, zoom is an integer somewhere between 1 (zoomed out as far as possible) and 20 (zoomed in as far as possible), so let’s round down to make sure the zoom level is big enough to capture the entirety of our area:

zoom = Math.floor(Math.log2(156543.03392m/px * Math.cos(latitude * Math.PI / 180) * pixels / meters))

Or, if you’re doing it America-style (in miles, that is):

zoom = Math.floor(Math.log2(97.27130mi/px * Math.cos(latitude * Math.PI / 180) * pixels / miles))

So, to demonstrate, if you want to show a 4 mile area near Nuuk, Greenland (64.192426, -51.595502):

zoom = Math.floor(Math.log2(97.27130mi/px * Math.cos(64.192426 * Math.PI / 180) * 500px / 4mi)) = 12

If, on the other hand, our 4 mile square is just outside of Quito, Ecquador (-0.174129, -78.422497):

zoom = Math.floor(Math.log2(97.27130mi/px * Math.cos(-0.174129 * Math.PI / 180) * 500px / 4mi)) = 13

Happy mapping!

--

--