How to “Show my current location on google maps, when I open the ViewController?” in Swift?

后端 未结 7 1549
梦如初夏
梦如初夏 2020-12-14 07:28

I am using Google maps sdk of iOS(Swift).

Has anyone know how to \"Show my current location on google maps, when I open the ViewController\"?

Actually it jus

7条回答
  •  天命终不由人
    2020-12-14 07:59

    • first add the following to your info.plist

      1. NSLocationWhenInUseUsageDescription
      2. LSApplicationQueriesSchemes (of type array and add two items to this array item 0 : googlechromes , item 1 : comgooglemaps
    • second go to https://developers.google.com/maps/documentation/ios-sdk/start and follow the steps till step 5

    • last thing to do after you set up every thing is to go to your ViewController and paste the following

      import UIKit
      import GoogleMaps
      
      class ViewController: UIViewController,CLLocationManagerDelegate {
      
          //Outlets
          @IBOutlet var MapView: GMSMapView!
      
          //Variables
          var locationManager = CLLocationManager()
      
          override func viewDidLoad() {
              super.viewDidLoad()
      
              initializeTheLocationManager()
              self.MapView.isMyLocationEnabled = true
          }
      
          func initializeTheLocationManager() {
              locationManager.delegate = self
              locationManager.requestWhenInUseAuthorization()
              locationManager.startUpdatingLocation()
          }
      
          func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
      
              var location = locationManager.location?.coordinate
      
              cameraMoveToLocation(toLocation: location)
      
          }
      
          func cameraMoveToLocation(toLocation: CLLocationCoordinate2D?) {
              if toLocation != nil {
                  MapView.camera = GMSCameraPosition.camera(withTarget: toLocation!, zoom: 15)
              }
          }
      
      }
      

    ( don't forget to add a view in the storyboard and connect it to the MapViw)

    now you can build and run to see your current location on the google map just like when you open the Google Map App

    enjoy coding :)

提交回复
热议问题