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.

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

  1. But you doo get additional data with these offers which is probably as much if not more than you would have gotten on uncazpped anyway.

  2. VPS Hosting has never been extra dependable as Evolution Host has
    pioneered the most complete, all encompassing and easily greatest VPSDDoS Protection in the business.

  3. The first homes will obtain service this fall and all neighborhoods will probably bbe
    wired by the end off 2013.

  4. It pays off to study auto insurance aas a wway to make an educated determination for your wants.

  5. It’s hard to find well-informed people for this subject, but
    you sound like you know what you’re talking about!

  6. The service iss thru Clear whose nicely-established 4G
    cellpular Internet infrastructure is obttainable in most cities in Washingtoon State.

  7. The nutritional deficiency of magnesium alone or together with
    that of calcium can result in osteoporosis.

  8. In emergency situations, your landlord cann enter your
    property without prior notice, even (and particularly) in case
    you are not dwelling at the time.

  9. But he’s calling them to onne thing, the clergymen and spiritual instructed
    the fifth graders.

  10. Thanks for sharing your thoughts about blog.

  11. emergency situations, your landlord cann enter your
    property without prior notice, eve

  12. When the refill season began on Apriul 1, working gasoline shares have been 874Bcf above the 5-12 months average.

  13. Just enter the username of your recreation after which
    choose the variety of free Pokemon go coins that you
    must add to your account.

  14. Based on researches, an increase in temperature will cause fungi decomposition to take
    place and will let off one-product of decomposition, carbon dioxide.
    Try to mimic as much of the journey in advance like a.

    These primates are only identified in Rwanda,
    Uganda and Congo.

  15. Get inventive and customise your football boots with laser etching to really say what you want to say. ” The story focuses on SEC programs, and Texas A&M is in the SEC now. You had a blast shopping for you football team kits.

  16. Atlantic broadband won’t just joun you to the remainder of the world, but will also give you the utmost service it has to offer.

  17. Thank you very much for tthe idea, howevcer my question is i’m having nokia c200 handset did I can surf internet by means of it by way of pc.

  18. There are many work from home Iternet enterprise ideas
    and opportunities to ewrn a living at home.

  19. Another thing for being maxed level is when you try to participate in player vs.
    Most importantly, we always ensure the clients are given written confirmation that
    they own the domain name, we are merely managing it on their behalf.

    There’s no point reading a long review of a popular provider if
    you don’t understand what’s being discussed, so giving
    yourself some overall knowledge on broadband before reading up on reviews
    is a good idea.

  20. An attention-grabbing characteristic of the MMORP games is the activity of conveying information and the
    genuine economy that can be built up between the players.
    Most importantly, we always ensure the clients are given written confirmation that they own the domain name, we are merely managing it on their behalf.
    Despite some of the language barriers by non-English speaking gamers, Ran Online is primarily an overall enjoyable MMORPG experience.

  21. Wrinkles, wonderful traces, and other blemishes on your pores and skin ultimately add aas
    much as make your skin look outdated and unhealthy.

  22. The last thing to do is move back to Redcliffe Castle and talk to
    Bann Teagan. com I will link you to below for anyplace near you or book a trip for the best areas that follow:.
    While pedaling, simply lift your body off of the seat.

  23. The Pyramid Mountain which is 3,000 feet offers a
    grand view on its ridgeline hike toward an aircraft spotting station used during the World War II.
    At that time, one month was only 20 days and a day was only 18 hours long.
    Being associated with the reputed remote pc support service provider Qresolve, I have resolved thousands of tech issues for
    our customers from worldwide.

  24. The last thing to do is move back to Redcliffe
    Castle and talk to Bann Teagan. But for those who
    prefer to be on the safe side and like everything to be perfect.

    The remote wipe feature on OS X Mountain Lion allows you to remove all your data from the Mac and go for a
    default restoration.

  25. The importance of a great community cannot be understated, it’s what keeps people coming back.
    By not at least providing opportunities for ample PVP,
    even the PVE people start to leave. There are many genres and to list just a
    few they cover Fantasy, Shooter, Racing, Post-apocalyptic and the list goes on.

  26. In the Guinness Book of World Records (2008), the title of ‘The Most Expensive Virtual Object” went to Club Neverdie which is an asteroid space resort in the Entropia Universe. I’m talking about your 14 year old high school graduate saying “I just don’t feel like I’m
    ready for college courses yet” then feeling comfortable enough to open up about her reasons. The users enjoy the feeling of accomplishment after being able to complete the adventure.

  27. In this article, let’s explore all about the mmorpg games played in the browser.
    It looks quite odd against the languid lushness and Gothic majesty of the
    rest of the game. As the name explains, it has a three dimensional
    screen that doesn’t require glasses to see the
    3D effects.

  28. Entertainment is important for people from all age teams
    no matter their occupation or background.

  29. Thank you, I’ve recently been searching for information approximately this topic for a while and
    yours is the best I have found out so far. However,
    what about the conclusion? Are you positive in regards to the supply?

  30. Frequent Sense, and Common Sense Media are registered emblems, and Widespread Sense Training, Widespread Sense
    Kids Action, and different associated names and logos are trademarks of Widesppread Senwe Media, a 501(c)(three) nonprofit organization (FEIN 41-2024986).

  31. Delhi Metro passengers throughout the NCR region will
    thus have the ability to expertise excessive speed brosdband byy simply logging
    onto tthe internet via a devoted App.

  32. A DSL service supplier will set up the service inside an affordable
    amount of time, so that yoou could be browsing the Internet quickly after signing up.

  33. Good info. Lucky me I reach on your website by accident, I bookmarked it.

  34. Good info. Lucky me I reach on your website by accident, I bookmarked it.

  35. I would like to thnkx for the efforts you have put in writing this blog. I am hoping the same high-grade blog post from you in the upcoming as well. In fact your creative writing abilities has inspired me to get my own blog now. Really the blogging is spreading its wings quickly. Your write up is a good example of it.

  36. 精米機を推奨してます。意図は自宅というのは玄米を知っている農家から購入して30kgをコイン精米機で精米して頂いていたのですが8月前後の暑い日の保存で虫が発生するようになり自宅で少量を精米状況になりました。家庭精米機をセレクトしたのは評判だからです。

  37. Meskipun demikian banyak orang mempertanyakan apakah mereka dapat menyalin game PS3 ke hard drive sehingga game asli dapat disimpan di sebuah tempat yang aman. Don’t’ forget to click on the Slide Show and
    Video to your left. “There have been three major grants for the project.

  38. Hi there mates, how is all, and what you want to say about this post,
    in my view its really amazing for me.

  39. Imóvel de fundos , sol da manhã, vista livre para
    parque aquático do tijuca e sumaré, sala , 2 quartos, banheiro
    social, cozinha, área e sujeição completa de empregada e também 2 vagas na escritura.

  40. Properly, stopp doing that proper now!

  41. Prohibited Items.

  42. Their bones were used for tools; their skins have been made
    inhto heat cllothes and the sinew (a tough fibrous tissue) to holdd
    collectively buildings.

Leave a Reply