Google Maps API calls from Cocoa

This is the first post of a serie in which I will present some useful (and often trivial) stuff I’m implementing in Cocoa for my (hopefully) upcoming app.

The basic idea is to present short snippets of code to do something.

In this case, to get a Google Static Map representing the world (but could be refactored easily to customize the view) in an NSImage object.

The code is available on the full post.

- (NSImage*) worldMapWithSize:(NSSize) size
              {
                 NSImage* result = [NSImage alloc];
              
                 // The Google Maps Static images are limited to 512 pixels, on both width and height
                 // If we pass a size exceeding this limit, we'll get only an error code
                 // Other possibility : get serious and avoid this limitation by requesting several images and compositing in one
                 size.width = size.width > 512 ? 512 : size.width;
                 size.height = size.height > 512 ? 512 : size.height;
              
                 NSMutableString* urlString = [NSMutableString stringWithString:@"http://maps.google.com/staticmap?"];
                 // We want to display the world map : setting the zoom at 1
                 [urlString appendString:@"zoom=1"];
                 // Center the map on a point : input your latitude and longitude here
                 [urlString appendString:@"&center=0,0"];
                 // Set the image size : widthxheight
                 [urlString appendString:@"&size="];
                 [urlString appendString:[[NSNumber numberWithInt:size.width] stringValue]];
                 [urlString appendString:@"x"];
                 [urlString appendString:[[NSNumber numberWithInt:size.height] stringValue]];
                 // And last but not least : your Google API Key
                 [urlString appendString:@"&key="];
                 [urlString appendString:[self googleMapsAPIKey]];
              
                 // Now let's the magic do the rest !
                 [result initWithContentsOfURL:[NSURL URLWithString:urlString]];
              
                 return result;
              }
Back