Installing Google Maps SDK
- Add the Google Maps SDK to your project using CocoaPods. First, ensure that CocoaPods is installed on your system, and your project is set up to use CocoaPods.
- Add the following line to your Podfile:
pod 'GoogleMaps'
- Run
pod install to install the SDK. Make sure to use the generated .xcworkspace file from now on instead of the standard .xcodeproj project file.
Import Libraries
- Open your project's AppDelegate.swift file. Import the Google Maps library by adding the following line at the top of the file:
import GoogleMaps
Configure API Key
- Within the
application(\_:didFinishLaunchingWithOptions:) function, initialize the SDK by providing your API key:
GMSServices.provideAPIKey("YOUR_API_KEY")
Add Map View to Storyboard
- In your main storyboard, drag a UIView onto the view controller.
- Select the UIView, open the Identity inspector, and set its class to
GMSMapView.
- Create an IBOutlet connection for the newly added view in your view controller.
Configuring the Map View
- In the associated ViewController.swift file, initialize the map view and set its camera properties:
@IBOutlet weak var mapView: GMSMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Set the initial location to a specific place (e.g., Sydney)
let camera = GMSCameraPosition.camera(withLatitude: -33.8688, longitude: 151.2093, zoom: 10.0)
mapView.camera = camera
}
Customizing the Map
- To add a marker, create an instance of
GMSMarker and attach it to the map:
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: -33.8688, longitude: 151.2093)
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = mapView
- You can customize the appearance and behavior of markers and the map itself via properties and methods offered by the
GMSMapView and GMSMarker classes.
Enabling Additional Features
- To enrich user interaction, enable features like traffic, indoor mapping, or current location by leveraging properties of
GMSMapView as follows:
mapView.isTrafficEnabled = true
mapView.isMyLocationEnabled = true
- Be aware that enabling location tracking will require user permissions.
Handling User Input
- You can handle map events, such as taps or movements, by implementing delegate methods. First, set your view controller class to conform to
GMSMapViewDelegate, and secondly, assign the map view delegate:
mapView.delegate = self
- Then, implement desired methods such as
mapView(\_:didTapAt:):
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
print("You tapped at \(coordinate.latitude), \(coordinate.longitude)")
}
- These methods allow picking up on user interactions and responding appropriately, which makes your map responsive and interactive.