How to use Google map sdk with iOS using swift

Various iOS apps use Google Maps. This is a very familiar feature, so I have decided to plan a crucial guide on the Google Maps SDK for iOS. This blogs covers the whole thing that you may want to know.

Installation

Previously, we start coding; we must install the Google Maps iOS SDK first. You may desire some other dependency manager, but I would recommend CocoaPods.

Build a Podfile inside your project root directory, and copy the following code:

source 'https://webnexs.com/CocoaPods/Specs.git'
target 'YOUR_TARGET_NAME' do
 pod 'GoogleMaps'
end

All you want to do is changing the YOUR_TARGET_NAME string with a real value. Save the file and close it. Release the terminal and cd to the root directory of the project, then type pod install. You are completed

Get an API key

To utilize the Google Maps iOS SDK, you will require an API Key. To create the key you will want to stay the Google API Console.
Build a project, and go to ‘Credentials’.

Then, tap ‘Generate Credentials’ and pick API Key. You will want to offer your projects bundle id. The key is generated by the unique bundle id, so if it’s altered, the Google Maps services

Navigate to your project, and in your AppDelegate.swift class include import GoogleMaps. Then, copy the following code to application(_:didFinishLaunchingWithOptions:)

GMSServices.provideAPIKey(“YOUR_API_KEY“)

GMSServices.provideAPIKey("YOUR_API_KEY")

Step 1 — include a map

I will establish by showing you how to set up the map together with a basic marker. The code that you will observe here is tested in parallel as I write.

Now visit your UIViewController (where you want to include the map). Build a custom UIView with the size you need. Allocate the GMSMapView class as a Custom Class to the UIView (observe the screenshot below). Also, don’t forget to connect the delegate.

Finally, some code!

Let’s acquire back to the UIViewController and write some code.
In the below snippet, I have included the whole class so you can get a better picture of what is going on.

GMSCameraPosition explains the map which coordinates to take as a center point. To demonstrate a simple marker on the map, use the showMarker() function.

At the ending of the file, include an extension which will “store” the GMSMapViewDelegate methods that we require.

import UIKit
import GoogleMaps

class ViewController: UIViewController {

@IBOutlet fileprivate weak var mapView: GMSMapView!
 
 override func viewDidLoad() {
 super.viewDidLoad()
 let camera = GMSCameraPosition.camera(withLatitude: 37.36, longitude: -122.0, zoom: 6.0)
 mapView.camera = camera
 showMarker(position: camera.target)
 }
 
 func showMarker(position: CLLocationCoordinate2D){
 let marker = GMSMarker()
 marker.position = position
 marker.title = "Palo Alto"
 marker.snippet = "San Francisco"
 marker.map = mapView
 }
}
extension ViewController: GMSMapViewDelegate{
 
}

Step 2 — Delegate methods

I will now initiate you to some GMSMapViewDelegate methods and their powers.

GMSMarker InfoWindow

In Google Maps, an InfoWindow is a popup window with additional information about a given location. It is shown when the user taps on the marker we included above.

Our InfoWindow is customizable. You can attach your own UIView with whatever components you require.

I have note down an example execution. This assumes in most cases people will use a custom InfoWindow,

extension ViewController: GMSMapViewDelegate{
 /* handles Info Window tap */
 func mapView(_ mapView: GMSMapView, didTapInfoWindowOf marker: GMSMarker) {
 print("didTapInfoWindowOf")
 }
 
 /* handles Info Window long press */
 func mapView(_ mapView: GMSMapView, didLongPressInfoWindowOf marker: GMSMarker) {
 print("didLongPressInfoWindowOf")
 }

/* set a custom Info Window */
 func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
 let view = UIView(frame: CGRect.init(x: 0, y: 0, width: 200, height: 70))
 view.backgroundColor = UIColor.white
 view.layer.cornerRadius = 6
 
 let lbl1 = UILabel(frame: CGRect.init(x: 8, y: 8, width: view.frame.size.width - 16, height: 15))
 lbl1.text = "Hi there!"
 view.addSubview(lbl1)
 
 let lbl2 = UILabel(frame: CGRect.init(x: lbl1.frame.origin.x, y: lbl1.frame.origin.y + lbl1.frame.size.height + 3, width: view.frame.size.width - 16, height: 15))
 lbl2.text = "I am a custom info window."
 lbl2.font = UIFont.systemFont(ofSize: 14, weight: .light)
 view.addSubview(lbl2)

return view
 }
}

didTapInfoWindowOf() identifies when the user taps on the InfoWindow.

markerInfoWindow() includes the custom UIView that we want to display to the marker.

didLongPressInfoWindowOf() identifies when the InfoWindow has been long pressed.

Drag GMSMarker

An additional interesting feature in GMSMapViewDelegate is the capability to drag the marker. This can be completed with a minimal amount of code.

All you have to do is turn on the “switch”, by calling marker.isDragabble=trueon the marker formed above.

In order to drag the marker, you will want to use a long press. If you want to be notified when the user starts and ends dragging, you can execute these three delegate methods:

extension ViewController: GMSMapViewDelegate{
 
 //MARK - GMSMarker Dragging
 func mapView(_ mapView: GMSMapView, didBeginDragging marker: GMSMarker) {
 print("didBeginDragging")
 }
 func mapView(_ mapView: GMSMapView, didDrag marker: GMSMarker) {
 print("didDrag")
 }
 func mapView(_ mapView: GMSMapView, didEndDragging marker: GMSMarker) {
 print("didEndDragging")
 }
}

didBeginDragging  informs once — when the dragging has started.

didDrag informs while the marker is being dragged.

didEndDragging informs once — when the dragging has ended.

GMSMarker position

What if you want to modify the GMSMarker position while the user is tapping on the map? fine, GMSMapViewDelegate provides a solution for that as well. A single delegate method can interrupt the manages (latitude and longitude) of the tapped area. It resolve then allocate their values to the marker.

extension ViewController: GMSMapViewDelegate{
 func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D){
 marker.position = coordinate
 }
}

didTapAt() returns the synchronize from the tapped area on the map

Step 3 — Adding shapes

The Google Maps iOS SDK creates it easy to draw a shape. I will envelop how to draw with polylines, polygons and circles.

Polylines

Shapes can be construct using lines. By using ‘polylines’,we can draw lines in Google Maps. The object that will assist us with the drawing is called GMSPolyline.

To form a polyline, you will want to create a path using GMSMutablePath. It requires two or more points to start creating a path.

func drawRectange(){
 /* create the path */
 let path = GMSMutablePath()
 path.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))
 path.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.0))
 path.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.2))
 path.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.2))
 path.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))
 
 /* show what you have drawn */
 let rectangle = GMSPolyline(path: path)
 rectangle.map = mapView
}

By using the above example, you will get a rectangular shape like which is shown in the above example.

Some other useful tips:

To eradicate a polyline from the map, call mapView.clear().

You can modify the color of the line by using polyline.strokeColor=.black.

Modify the width of the line by calling polyline.strokeWidth=3.

Polygon

Polygon is almost the same as polylines. It works using the similar approach, with a little differences.

For example, GMSPolygonwill draw a shape. Then you can use fillColor to fill in the drawn area. The following are the examples:

func polygon(){
 // Create a rectangular path
 let rect = GMSMutablePath()
 rect.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.0))
 rect.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.0))
 rect.add(CLLocationCoordinate2D(latitude: 37.45, longitude: -122.2))
 rect.add(CLLocationCoordinate2D(latitude: 37.36, longitude: -122.2))
 
 // Create the polygon, and assign it to the map.
 let polygon = GMSPolygon(path: rect)
 polygon.fillColor = UIColor(red: 0.25, green: 0, blue: 0, alpha: 0.2);
 polygon.strokeColor = .black
 polygon.strokeWidth = 2
 polygon.map = mapView
}

Radius (circle)

The concluding shape we will look at is a circle. This is perhaps the easiest shape then other, while it’s always the similar!

To reach this, we want to use theGMSCircle class. Here, we are not passing a path. As a substitute, we use one coordinate to state the circle’s center. We also define a radius (measured in meters).

func circle(){
 let circleCenter = CLLocationCoordinate2D(latitude: 37.35, longitude: -122.0)
 let circ = GMSCircle(position: circleCenter, radius: 1000)
 circ.map = mapView
}

TheGMSCircle class includes the similar properties as the polygon, includingfillColor , strokeColor and strokeWidth.

Step 4 — Properties and Settings

This section will envelop a few properties and settings that are often use when using Google Maps in your app. Let’s take a look at them.

Change marker icon

The GMSMarker includes two different properties for modifying the marker icon.

marker.icon=UIImage(named: “image.png”) in this approach, you overtake an image filename. This change the default one.

marker.iconView=customView You can also include a custom view alternative of an image. This can be used for more complex markers. For example, you may want to include few animations, or multiple components (instead of a single image).

Add ‘My Location’ button

The ‘My Location’ button shown in the bottom right corner. Selecting the button will animate the map to display the user’s current location.

To include this, set mapView.settings.myLocationButton = true. The button will shown.

Zoom controls

Google Maps SDK for iOS doesn’t offers inbuilt zoom controls (but the Android SDK does). You will want to write your own logic instead.

All you want to perform is include two buttons with ‘+’ and ‘-’ icons. When tapped, these will call mapView.animate(toZoom: zoom).

Control gestures

You can switch on or off any sign that you can observe on the map. For example, you may want to disable zooming, or turn off scrolling.

4 gestures available to you:

mapView.settings.scrollGestures = false
mapView.settings.zoomGestures = false
mapView.settings.tiltGestures = false
mapView.settings.rotateGestures = false

Last Update: September 19, 2018  

September 19, 2018   55   Nandini R    Local Storage    
Total 0 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Google+
https://www.webnexs.com/blog/kb/use-google-map-sdk-ios-using-swift
Twitter
LinkedIn