Warning: join(): Invalid arguments passed in /home/troyb/troybrant.net/blog/wp-content/themes/hybrid-hacked/hybrid-hacked/library/functions/breadcrumbs.php on line 79

MKMapView and Zoom Levels: A Visual Guide

So, how exactly does the code provided in the previous post work? What follows is a visual explanation of Google Maps, zoom levels, and how you go about adding support for zoom levels to the MKMapView class.

Round to Flat

This is planet Earth:

As you may know, it is round.

To create a map of the Earth, the curved surface must be projected onto a flat surface. There are many map projections that attempt to flatten the Earth. There are distortions inherent to every projection, but each map projection aims to preserve at least one quality from the original curved representation.

Some projections preserve area, such as the Mollweide projection:

Equirectangluar projections preserve distance between the meridians:

The Mercator projection stretches out the poles in order to preserve locally measured angles:

Google uses the Mercator projection to render Google Maps:

Mercator Math

The Mercator projection converts latitude (φ) and longitude (λ) coordinates to pixel values. It uses math:

You don’t have to understand the math; just know that it converts latitudes and longitudes to pixels.

But, where are these pixels? Well, it depends on your zoom level.

Zoom Levels

At zoom level 0, Google displays the world in a single 256 pixel by 256 pixel tile:

At zoom level 1, Google doubles the area of the map while keeping the tile size constant. So, the map grows to 512 pixels by 512 pixels and uses four tiles:

At zoom level 2, Google doubles the area again. The map grows to 1024 pixels by 1024 pixels and uses sixteen tiles:

The pixel area continues to double at each zoom level, and when zoom level 20 is reached, the map is 536,870,912 pixels by 536,870,912 pixels. It has so many tiles we won’t bother to count them:

Latitudes and Longitudes to Pixels

As part of the PHP Static Maps project, Mike Tuupola wrote some code that converts latitudes and longitudes to pixels at zoom level 20. The code is easily ported to Objective-C:

// Convert latitude and longitude to pixel values at zoom level 20

#define MERCATOR_OFFSET 268435456 /* (total pixels at zoom level 20) / 2 */
#define MERCATOR_RADIUS 85445659.44705395 /* MERCATOR_OFFSET / pi */

x = round(MERCATOR_OFFSET + MERCATOR_RADIUS * longitude * M_PI / 180.0);
y = round(MERCATOR_OFFSET - MERCATOR_RADIUS * logf((1 + sinf(latitude * M_PI / 180.0)) / (1 - sinf(latitude * M_PI / 180.0))) / 2.0);

To be honest, I haven’t taken the time to wrap my head around how this code works. But, knowing that it does work, we can now take any latitude and longitude and figure out its pixel coordinates at zoom level 20. For instance, here are the pixel coordinates of several cities around the world:

Add an iPhone

Say we place an iPhone on top of Anchorage, Alaska at zoom level 20:

In the iPhone shown above, the map size is 320 pixels by 460 pixels. Since we know the map dimensions and center coordinate in pixels, we can easily compute the pixel coordinates of the top-left corner relative to the center pixel coordinate:

We can find the relative position of the top-right and bottom-left pixel coordinates as well:

The PHP Static Maps code also provides code to go from pixels at zoom level 20 to latitudes and longitudes:

// Convert pixel values at zoom level 20 to latitude and longitude

latitude = (M_PI / 2.0 - 2.0 * atan(exp((round(pixelY) - MERCATOR_OFFSET) / MERCATOR_RADIUS))) * 180.0 / M_PI;
longitude = ((round(pixelX) - MERCATOR_OFFSET) / MERCATOR_RADIUS) * 180.0 / M_PI;

We can use this code to convert the corners from pixel coordinates to latitudes and longitudes:

As shown above, using the corner coordinates, we can compute the latitudinal and longitudinal distances. These distances are exactly what we need to construct an MKCoordinateSpan. That span, in turn, is used to initialize the region property of an MKMapView:

// Create an MKCoordinateSpan to initialize the map’s region

MKCoordinateSpan span = MKCoordinateSpanMake(latitudeDelta, longitudeDelta);
MKCoordinateRegion region = MKCoordinateRegionMake(centerCoordinate, span);
[mapView setRegion:region animated:NO];

And you’re done!…That is, if you want to see zoom level 20. What do you do when your user wants to see the map at zoom level 19 instead of 20?

Scaling using Zoom Levels

Relative to zoom level 20, zooming out one level doubles the area visible on the map.

For example, consider the image below. On the left is Anchorage at zoom level 19, and on the right are the 4 iPhones at zoom level 20 it would take to display the same amount of area:

If we move up another level, the area doubles again. Consider the following image. On the left is Anchorage at zoom level 18, and on the right are the 16 iPhones at zoom level 20 it would take to display the same amount of area:

Since the area doubles at each zoom level, we can define the following exponential relationship between the zoom level and the area covered by the map:

// Compute a scaling factor that will take us from any zoom level to zoom level 20

NSInteger zoomExponent = 20 - zoomLevel;
double zoomScale = pow(2, zoomExponent);

double scaledMapWidth = mapSizeInPixels.width * zoomScale;
double scaledMapHeight = mapSizeInPixels.height * zoomScale;

For instance, here is Anchorage at zoom levels 20, 19, and 18. The map’s width and height in pixels are unaltered:

After computing the zoom scale factor, we can apply it to each map to determine its dimensions at zoom level 20:

After we compute these new dimensions, we plug them into the algorithm for finding the coordinates of the map corners.

An Example: Zoom Level 18

For instance, say we take the map at zoom level 18:

Let’s drop the matrix of phones but keep the scaled width and height:

We find the top-left corner just like we did before, except now we use the scaled width and height:

Similarly, we use the scaled width and height for finding the top-right and bottom-left corners as well:

Using the pixel and latitude and pixel and longitude helper methods, we can compute the coordinates of the corners and the distance between them:

These delta values are used to initialize the map’s region property, and the map zooms to the level you specify.

That’s a Wrap

Be sure to check out the previous post for the full code that adds support for zoom levels to MKMapView.

If you are interested in learning more from someone much smarter than I am, check out these posts from Charlie Savage, a programmer and cartographer extraordinaire:

Much of what I know about maps is from these articles, and I highly recommended checking them out if you want to learn more about how Google Maps works under the hood.

118 Responses to “MKMapView and Zoom Levels: A Visual Guide”

  1. Before utilizing that suspect powdered creamer within the auto mechanic’s waiting room or at the office’s coffee bar, make sure to examine the components checklist.

  2. Insurance firms aren’t normally famend for his orr her extreme compassion and understanding.

  3. Then again, you doo not wish to purchase one which’s too eexpensive because that kills the point
    of saving cash in your Gamecube games.

  4. Hi I am so thrilled I found your blog, I really found you by accident, while I was looking on Yahoo for something else, Regardless I am here now and would just like to say thank you for a marvelous post and
    a all round thrilling blog (I also love the theme/design), I don’t have time to go through it all at the moment but I have book-marked it and also included your RSS feeds, so when I have time I will be back to read a
    great deal more, Please do keep up the awesome work.cheap
    nfl jerseys

  5. Work spaces ccan get cluttered shortly, so ensure that you employ one in every of these professional providers to get rid of dust, take away
    muddle, and hold every little thing neat annd tidy.

  6. For those who do not know, APK install files are likeexe files on Windows, and let telephone owners install applications and games on their Android devices without obtaining to go
    via the Google Play Store.

  7. Since Nintendo has however to push-out Super Mario Run to the Google Play Shop,
    these APK databases are just about generally fake.

  8. Gather equivalent infrastructures in a single spot so you can preserve track of upgrades very easily.

  9. Be stealthy and a bit random.

  10. The goal of the cheats is critical as it pertains to coughing on the
    marvel contest.

  11. As you can see, they have invested a lot of money so that they
    could get the Star Wars license and now they have to get their money’s worth.
    Firstly, you may have a classic Star Wars event with the original Episodes (IV, V,
    and VI) showing repeatedly throughout the party. Ensure that you have
    the guest list ready with you, so that you do not miss out on any important guest.

  12. Decidijng which photographer you utiloze in your special occasions is actually aan important resolution.
    You need to hire someone who not only has a character you will get together with however someoe that may even produce quality
    pictures within the style thzt you’ve requested.

  13. But when adding a couple of chocolate chips too your weight loss plan meals reains you from feasting on a hunk of rreal chocolate cake,
    then in my opinion, that is value it. You possibly can additionally
    use the eating regimen’s chips and pretzelps for those who
    werde craving something salty.

  14. Matthew, before I began writing on-line I used to be incomes pretty well from my prints articles.

  15. These days, it’s often used bby accountants to handle large monetary
    accounts of medical places of work. With the assistance of medical Software, account administration has becfome easy, smooth annd
    exact. If you’re seeking too buy software, you have to know about its options according to yoour necessities.
    You can install more features in response to your basic requirements.
    Typically, the highly detailed software is used
    in large medical organizations or hospitals to deal witth
    amount of daya and mmonetary transactions.

  16. Ahaa, its nice conversation regarding this piece of writing here at this
    website, I have read all that, so now me also commenting here.cheap nfl jerseys

  17. The tougher youu push, the farther you might be extending your writing ability and
    ponderijng process. Subsequently, I have concluded that writing on-line articles is not going
    to solely enable you to with your reminiscence, howeever it provides you with with a slightly giant uptick in cognitive expertise.
    Certainly I hope you will please think about all this and think
    on it.

  18. Definitely consider that that you said. Your favourite justification seemed to be
    at the internet the easiest factor to bear in mind of.
    I say to you, I certainly get annoyed at the same time as folks think about
    issues that they just don’t know about. You controlled
    to hit the nail upon the highest and also defined out the entire
    thing with no need side effect , folks could take a
    signal. Will probably be again to get more. Thank you

Leave a Reply