Google Maps SDK for iOS

Map Objects

Note: This document describes how to add a Google Map to an iOS application. If you would like to know how to launch the Google Maps standalone application, please refer to the URL Scheme documentation.

Maps are represented in the API by the GMSMapView class, a subclass of UIView. The map is the most significant object in the Google Maps SDK for iOS, and provides necessary methods for adding, removing and managing other objects such as markers and polylines.

Introduction

The Google Maps SDK for iOS allows you to display a Google map in your iOS application. These maps have the same appearance as the maps you see in the Google Maps iOS app, and the SDK exposes many of the same features.

In addition to mapping functionality, the API also supports a range of interactions that are consistent with the iOS UI model. For example, you can set up interactions with a map by defining responders that react to user gestures, such as tap and double-tap.

The key class when working with a Map object is the GMSMapView class. GMSMapView handles the following operations automatically:

  • Connecting to the Google Maps service.
  • Downloading map tiles.
  • Displaying tiles on the device screen.
  • Displaying various controls such as pan and zoom.
  • Responding to pan and zoom gestures by moving the map and zooming in or out.
  • Responding to two finger gestures by tilting the viewing angle of the map.

In addition to these automatic operations, you can control the behavior and appearance of the map through the properties and methods exposed by the GMSMapView class. GMSMapView allows you to add and remove markers, ground overlays and polylines, change the type of map that is displayed, and control what is shown on the map through the GMSCameraPosition class.

Add a Map

The basic steps for adding a map are:

  1. (Once) Follow the steps in Getting Started to get the SDK, obtain a key and add the required frameworks.
  2. In your AppDelegate, provide your API key to the provideAPIKey: class method on GMSServices.
  3. Create or update a ViewController. If the map will be displayed when this view controller becomes visible, be sure to create it within the loadView method.
    1. Create a GMSCameraPosition object that specifies the center and zoom level of the map. When you instantiate the GMSMapView object, you must pass the GMSCameraPosition object as a required parameter.
    2. Create and instantiate a GMSMapView class using the GMSMapView mapWithFrame: method. If this map is to be used as the view controller's only view, then CGRectZero could be used as the map's frame — the map will be resized automatically.
    3. Set the GMSMapView object as the view controller's view, e.g. self.view = mapView_;.

The below example adds a map, centered at downtown Singapore, to an app.

#import "DemoViewController.h"
#import <GoogleMaps/GoogleMaps.h>

@implementation DemoViewController {
  GMSMapView *mapView_;
}

- (void)loadView {
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:1.285
                                                          longitude:103.848
                                                               zoom:12];
  mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
  self.view = mapView_;
}

@end

Once you've followed these steps, you may further configure the GMSMapView object.

Map Types

You can customize your map with one of several map types. A map's type governs the overall representation of the map. For example, an atlas usually contains political maps that focus on showing boundaries, and road maps that show all of the roads for a city or region. The Google Maps SDK for iOS offers the following types of maps:

Type Value Description
Normal kGMSTypeNormal Typical road map. Roads, some man-made features, and important natural features such as rivers are shown. Road and feature labels are also visible. This is the default map mode in Google Maps for iOS.
Hybrid kGMSTypeHybrid Satellite photograph data with road maps added. Road and feature labels are also visible. This map type can be enabled on the Google Maps app for iOS by turning on the Satellite view.
Satellite kGMSTypeSatellite Satellite photograph data. Road and feature labels are not visible. This mode is not available in Google Maps for iOS.
Terrain kGMSTypeTerrain Topographic data. The map includes colors, contour lines and labels, and perspective shading. Some roads and labels are also visible.
None kGMSTypeNone No map tiles. The base map tiles will not be rendered. This mode is useful in conjunction with tile layers. The display of traffic data will be disabled when the map type is set to none.

Change the Map Type

To set the type of a map, assign a new value to the GMSMapView.mapType property. For example, to display a satellite map type:

GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.8683
                                                        longitude:151.2086
                                                             zoom:6];
mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView_.mapType = kGMSTypeSatellite;

The chooser below shows a comparison of terrain, normal and hybrid maps for the same location:

Indoor Maps

At high zoom levels, the Google Maps SDK for iOS will show floor plans for indoor spaces such as airports, shopping malls, large retail stores, and transit stations. Indoor floor plans are integrated into the default map tiles for the 'normal' map type (kGMSTypeNormal), and are automatically enabled when the user zooms in, and fade away when the map is zoomed out.

You can disable indoor maps by setting the indoorEnabled property of GMSMapView to NO.

GMSMapView *mapView_;
mapView_.indoorEnabled = NO;

Alternately, you can disable just the Floor Picker control.

Adding Floor Plans

Floor plans are available in select locations. If floor plan data is not available for a building that you would like to highlight in your application, you can:

  • Add floor plans to Google Maps directly. This will make your plans are available to all users of Google Maps.
  • Display a floor plan as a Ground Overlay. This will enable only users of your application to view your floor plans.

Accessibility

By default, accessibility elements on the map are hidden. You may enable accessibility by setting the accessibilityElementsHidden property of GMSMapView to NO. This will cause accessibility elements to be generated for overlay objects (such as GMSMarker and info windows, GMSPolyline etc).

mapView_.accessibilityElementsHidden = NO;

This property is as per the informal UIAccessibility protocol, except that the default value in the Google Maps SDK for iOS is YES.

My Location

By default, no location data is shown on the map. You may enable the blue "My Location" dot and compass direction by setting myLocationEnabled on GMSMapView.

mapView_.myLocationEnabled = YES;

Enabling this feature will also provide the user's current location through the myLocation property. This property may not be immediately available - for example, if the user is prompted by iOS to allow access to this data. It will be nil in this case.

NSLog(@"User's location: %@", mapView_.myLocation);

Map padding

A Google Map is designed to fill the entire region defined by the GMSMapView. Several aspects of how the map appears and behaves are defined by the dimensions of the the view:

  • The camera's target will reflect the center of the padded region.
  • Map controls are positioned relative to the edges of the map.
  • Legal information, such as copyright statements or the Google logo appear along the bottom edge of the map.

You can add padding around the edges of the map using the GMSMapView.padding property. The map will continue to fill the entire container, but text and control positioning, map gestures, and camera movements will behave as if it has been placed in a smaller space. This results in the following changes:

  • Camera movements via API calls or button presses (e.g., compass, my location) will be relative to the padded region.
  • GMSMapView.projection will return a projection that includes only the padded region.
  • UI controls will be offset from the edge of the container by the specified number of points.

Padding can be helpful when designing UIs that overlap some portion of the map. For example, in the below image, the map is padded along the top and right edges. Visible map controls and legal text will be displayed along the edges of the padded region, shown in green, while the map will continue to fill the entire container, shown in blue. In this example, you could float a menu over the right side of the map without obscuring map controls.

Map Padding

To add padding to your map, create a UIEdgeInsets object and pass it to the GMSMapView.padding property.

// Insets are specified in this order: top, left, bottom, right
UIEdgeInsets mapInsets = UIEdgeInsetsMake(100.0, 0.0, 0.0, 300.0);
GMSMapView *mapView_;
mapView_.padding = mapInsets;

Map Events

Google Maps SDK for iOS allows you to listen to events that occur on the map, such as camera change events or marker tap events.

To do this, you must implement the GMSMapViewDelegate protocol. Typically, you would implement this protocol on the view controller that displays the map. An example header file would look like:

#import <GoogleMaps/GoogleMaps.h>
#import <UIKit/UIKit.h>

@interface DemoViewController : UIViewController<GMSMapViewDelegate>
@end

When the GMSMapView is created, you may now set its delegate to your view controller. The GMSMapViewDelegate provides only optional methods; to listen to any particular event, you must implement the relevant method.

- (void)loadView {
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:1.285
                                                          longitude:103.848
                                                               zoom:12];
  mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
  mapView_.delegate = self;
  self.view = mapView_;
}

#pragma mark - GMSMapViewDelegate

- (void)mapView:(GMSMapView *)mapView
    didTapAtCoordinate:(CLLocationCoordinate2D)coordinate {
  NSLog(@"You tapped at %f,%f", coordinate.latitude, coordinate.longitude);
}

Camera position

The GMSMapViewDelegate allows users of the Google Maps SDK for iOS to listen to changes to the camera position used to render the map. There are three distinct events.

  • mapView:willMove: indicates that the camera position is about to change. If the gesture argument is set to YES, this is due to a user performing a natural gesture on the GMSMapView, such as a pan or tilt. Otherwise, NO indicates that this is part of a programmatic change - for example, via methods such as animateToCameraPosition: or updating the map's layer directly. This may also be NO if a user has tapped on the My Location or compass buttons, which generate animations that change the camera.

This method may be called several times before mapView:idleAtCameraPosition: is invoked, although this will typically only happen if animations and gestures occur at the same time - a gesture will cancel any current animation, for instance, and will call mapView:willMove: a second time.

  • mapView:didChangeCameraPosition: is called repeatedly during a gesture or animation, always after a call to mapView:willMove:. It is passed the intermediate camera position.

  • Finally, mapView:idleAtCameraPosition: is invoked once the camera position on GMSMapView becomes idle, and specifies the camera positon in question. At this point, all animations and gestures have stopped.

Applications might use this event to trigger a refresh of markers or other content being displayed on the GMSMapView, rather than e.g., reloading the content on every camera change.

For example, an application might clear the GMSMapView on move, and then reverse geocode the position the camera comes to rest on.

#pragma mark - GMSMapViewDelegate

- (void)mapView:(GMSMapView *)mapView willMove:(BOOL)gesture {
  [mapView clear];
}

- (void)mapView:(GMSMapView *)mapView
    idleAtCameraPosition:(GMSCameraPosition *)cameraPosition {
  id handler = ^(GMSReverseGeocodeResponse *response, NSError *error) {
    if (error == nil) {
      GMSReverseGeocodeResult *result = response.firstResult;
      GMSMarker *marker = [GMSMarker markerWithPosition:cameraPosition.target];
      marker.title = result.addressLine1;
      marker.snippet = result.addressLine2;
      marker.map = mapView;
    }
  };
  [geocoder_ reverseGeocodeCoordinate:cameraPosition.target completionHandler:handler];
}

Other events

To learn about the full list of methods on GMSMapViewDelegate, please see GMSMapViewDelegate.

Disable map gestures

You can disable the default gestures on the map by setting properties of the GMSUISettings class, which is available as a property of the GMSMapView. The following gestures can be enabled and disabled programmatically. Note disabling the gesture will not limit programmatic access to the camera settings.

  • scrollGestures — controls whether scroll gestures are enabled or disabled. If enabled, users may swipe to pan the camera.
  • zoomGestures — controls whether zoom gestures are enabled or disabled. If enabled, users may double tap, two-finger tap, or pinch to zoom the camera. Note that double tapping may pan the camera to the specified point.
  • tiltGestures — controls whether tilt gestures are enabled or disabled. If enabled, users may use a two-finger vertical down or up swipe to tilt the camera.
  • rotateGestures — controls whether rotate gestures are enabled or disabled. If enabled, users may use a two-finger rotate gesture to rotate the camera.

In the below example, both pan and zoom gestures have been disabled.

- (void)loadView {
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:1.285
                                                          longitude:103.848
                                                               zoom:12];
  mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
  mapView_.settings.scrollGestures = NO;
  mapView_.settings.zoomGestures = NO;
  self.view = mapView_;
}

Map Controls

The Google Maps SDK for iOS provides some built-in UI controls that are similar to those found in the Google Maps for iOS application. You can toggle the visibility of these controls using the GMSUISettings class. Changes made on this class are immediately reflected on the map.

Compass

The Maps SDK provides a compass graphic which appears in the top right corner of the map under certain circumstances. The compass will only ever appear when the camera is oriented such that it has a non-zero bearing. When the user clicks on the compass, the camera animates back to a position with bearing of zero (the default orientation) and the compass fades away shortly afterwards. The compass is disabled by default; you can enable the compass by setting the compassButton property of GMSUISettings to YES. However, you cannot force the compass to always be shown.

GMSMapView *mapView_;
mapView_.settings.compassButton = YES;

My Location button

The My Location button appears in the bottom right corner of the screen only when the My Location button is enabled. When a user clicks the button, the camera animates to focus on the user's current location if the user's location is currently known. You can enable the button by setting the myLocationButton property of GMSUISettings to YES.

GMSMapView *mapView_;
mapView_.settings.myLocationButton = YES;

Floor Picker

The Floor Picker control appears near the bottom right of the screen whenever an indoor map is featured prominently. When two or more indoor maps are visible the Floor Picker will correspond to the map nearest to the center of the screen. Each building has a default floor which will be selected when the picker is first displayed. You can choose a different floor by selecting it from the picker. You can disable the floor picker control by setting the indoorPicker property of GMSUISettings to NO.

GMSMapView *mapView_;
mapView_.settings.indoorPicker = NO;

Autentisering krävs

Du måste vara inloggad på Google+ för detta.

Du loggas in ...

Google Developers behöver ditt tillstånd att göra detta.