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

后端 未结 7 1543
梦如初夏
梦如初夏 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:35

    Swift 3.0 or above

    For displaying user location (Blue Marker) in GMS map View make sure you have got Location Permission and add this line

    mapView.isMyLocationEnabled = true
    
    0 讨论(0)
  • 2020-12-14 07:36

    You can use RxCoreLocation:

    import UIKit
    import GoogleMaps
    import RxCoreLocation
    import RxSwift
    
    class MapViewController: UIViewController {
        private var mapView: GMSMapView?
        private let disposeBag = DisposeBag()
        private let manager = CLLocationManager()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            manager.requestWhenInUseAuthorization()
            manager.startUpdatingLocation()
    
            let camera = GMSCameraPosition.camera(withLatitude: 0, longitude: 0, zoom: 17.0)
            mapView = GMSMapView.map(withFrame: .zero, camera: camera)
            view = mapView
    
            manager.rx
                .didUpdateLocations
                .subscribe(onNext: { [weak self] in
                    guard let location = $0.locations.last else { return }
                    let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude, longitude: location.coordinate.longitude, zoom: 17.0)
                    self?.mapView?.animate(to: camera)
                    self?.manager.stopUpdatingLocation()
                })
                .disposed(by: disposeBag)
        }
    }
    
    0 讨论(0)
  • 2020-12-14 07:45
    import UIKit
    import GoogleMaps
    import GooglePlaces
    import CoreLocation
    
    class ViewController: UIViewController,CLLocationManagerDelegate,GMSMapViewDelegate {
    
        @IBOutlet weak var currentlocationlbl: UILabel!
    
        var mapView:GMSMapView!
    
        var locationManager:CLLocationManager! = CLLocationManager.init()
        var geoCoder:GMSGeocoder!
        var marker:GMSMarker!
    
        var initialcameraposition:GMSCameraPosition!
        override func viewDidLoad() {
    
            super.viewDidLoad()
    
            // Do any additional setup after loading the view, typically from a nib.
    
            self.mapView = GMSMapView()
            self.geoCoder = GMSGeocoder()
            self.marker = GMSMarker()
            self.initialcameraposition = GMSCameraPosition()
    
            // Create gms map view------------->
            mapView.frame = CGRect(x: 0, y: 150, width: 414, height: 667)
            mapView.delegate = self
            mapView.isMyLocationEnabled = true
            mapView.isBuildingsEnabled = false
    
            mapView.isTrafficEnabled = false
            self.view.addSubview(mapView)
            // create cureent location label---------->
    
            self.currentlocationlbl.lineBreakMode = NSLineBreakMode.byWordWrapping
            self.currentlocationlbl.numberOfLines = 3
            self.currentlocationlbl.text = "Fetching address.........!!!!!"
    
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
            if locationManager.responds(to: #selector(CLLocationManager.requestAlwaysAuthorization))
            {
                self.locationManager.requestAlwaysAuthorization()
            }
            self.locationManager.startUpdatingLocation()
    
            if #available(iOS 9, *)
            {
                self.locationManager.allowsBackgroundLocationUpdates = true
            }
            else
            {
                //fallback earlier version
            }
    
            self.locationManager.startUpdatingLocation()
            self.marker.title = "Current Location"
            self.marker.map = self.mapView
    
            // Gps button add mapview
    
            let gpbtn:UIButton! = UIButton.init()
            gpbtn.frame = CGRect(x: 374, y: 500, width: 40, height: 40)
            gpbtn.addTarget(self, action: #selector(gpsAction), for: .touchUpInside)
            gpbtn.setImage(UIImage(named:"gps.jpg"), for: .normal)
            self.mapView.addSubview(gpbtn)
        }
    
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
        {
            var location123 = CLLocation()
            location123 = locations[0]
            let coordinate:CLLocationCoordinate2D! = CLLocationCoordinate2DMake(location123.coordinate.latitude, location123.coordinate.longitude)
            let camera = GMSCameraPosition.camera(withTarget: coordinate, zoom: 16.0)
    
            self.mapView.camera = camera
            self.initialcameraposition = camera
            self.marker.position = coordinate
            self.locationManager.stopUpdatingLocation()    
        }
    
        func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition)
        {
            self.currentAddres(position.target)
        }
    
        func currentAddres(_ coordinate:CLLocationCoordinate2D) -> Void
        {
            geoCoder.reverseGeocodeCoordinate(coordinate) { (response, error) in
    
                if error == nil
                {
                    if response != nil
                    {
                        let address:GMSAddress! = response!.firstResult()
    
                        if address != nil
                        {
                            let addressArray:NSArray! = address.lines! as NSArray
    
                            if addressArray.count > 1
                            {
                                var convertAddress:AnyObject! = addressArray.object(at: 0) as AnyObject!
                                let space = ","
                                let convertAddress1:AnyObject! = addressArray.object(at: 1) as AnyObject!
                                let country:AnyObject! = address.country as AnyObject!
    
                                convertAddress = (((convertAddress.appending(space) + (convertAddress1 as! String)) + space) + (country as! String)) as AnyObject
    
                                self.currentlocationlbl.text = "\(convertAddress!)".appending(".")
                            }
                            else
                            {
                                self.currentlocationlbl.text = "Fetching current location failure!!!!"
                            }
                        }
                    }
                }
            }
        }
    
    0 讨论(0)
  • 2020-12-14 07:47

    For Swift 3.x solution, please check this Answer

    First all of you have to enter a key in Info.plist file NSLocationWhenInUseUsageDescription

    After adding this key just make a CLLocationManager variable and do the following

    @IBOutlet weak var mapView: GMSMapView!
    var locationManager = CLLocationManager()
    
    class YourControllerClass: UIViewController,CLLocationManagerDelegate {
    
        //Your map initiation code 
        let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
        self.view = mapView
        self.mapView?.myLocationEnabled = true
    
        //Location Manager code to fetch current location
        self.locationManager.delegate = self
        self.locationManager.startUpdatingLocation()
    }
    
    
    //Location Manager delegates
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
        let location = locations.last
    
        let camera = GMSCameraPosition.cameraWithLatitude((location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!, zoom: 17.0)
    
        self.mapView?.animateToCameraPosition(camera)
    
        //Finally stop updating location otherwise it will come again and again in this delegate
        self.locationManager.stopUpdatingLocation()
    
    }
    

    When you run the code you will get a pop up of Allow and Don't Allow for location. Just click on Allow and you will see your current location.

    Make sure to do this on a device rather than simulator. If you are using simulator, you have to choose some custom location and then only you will be able to see the blue dot.

    0 讨论(0)
  • 2020-12-14 07:50

    Use this code,

    You miss the addObserver method and some content,

    viewDidLoad:

    mapView.settings.compassButton = YES;
    
    mapView.settings.myLocationButton = YES;
    
    mapView.addObserver(self, forKeyPath: "myLocation", options: .New, context: nil)
    
    dispatch_async(dispatch_get_main_queue(), ^{
        mapView.myLocationEnabled = YES;
      });
    

    Observer Method:

    override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
    
        if change[NSKeyValueChangeOldKey] == nil {
    
            let location = change[NSKeyValueChangeNewKey] as CLLocation
            gmsMap.camera = GMSCameraPosition.cameraWithTarget(location.coordinate, zoom: 16)
        }
    }
    

    hope its helpful

    0 讨论(0)
  • 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 :)

    0 讨论(0)
提交回复
热议问题