Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize "myLocationButton" of Google Maps for iOS Swift

I'm a newbie in iOS development. I want to create a custom button with the same functionality as the default button (myLocationButton) in Google Maps SDK for iOS. Can I do that? I can create the button but I don't know how to add action to track my current location and show the marker in the center of the screen. I'm using Swift 3.

-Here is the image-

Any help would be appreciated!

like image 367
user-unknown Avatar asked Dec 08 '16 13:12

user-unknown


2 Answers

You could implement the action like so:

func gotoMyLocationAction(sender: UIButton)
{
    guard let lat = self.mapView.myLocation?.coordinate.latitude,
          let lng = self.mapView.myLocation?.coordinate.longitude else { return }

    let camera = GMSCameraPosition.camera(withLatitude: lat ,longitude: lng , zoom: zoom)
    self.mapView.animate(to: camera)
}

This center your map to your current position if they exists. Hope that helps.

Be sure the position detection on your GMSMapView is enabled

self.mapView.isMyLocationEnabled = true
like image 74
Thomas G. Avatar answered Nov 14 '22 18:11

Thomas G.


Update Swift 4 for @Thomas answer, with GoogleMapSDK 2.7.0

func didTapMyLocationButton(for mapView: GMSMapView) -> Bool {

    guard let lat = googleMapView.myLocation?.coordinate.latitude,
        let lng = googleMapView.myLocation?.coordinate.longitude else { return false }

    let camera = GMSCameraPosition.camera(withLatitude: lat ,longitude: lng , zoom: userMapZoom)
    googleMapView.animate(to: camera)

    return true

}
like image 41
Majd Sabah Avatar answered Nov 14 '22 19:11

Majd Sabah