【问题标题】:How to "Show my current location on google maps, when I open the ViewController?" in Swift?如何“在我打开 ViewController 时在谷歌地图上显示我的当前位置?”在斯威夫特?
【发布时间】:2016-07-28 03:34:05
【问题描述】:

我正在使用 iOS(Swift) 的 Google maps sdk。

有谁知道如何“在我打开 ViewController 时在谷歌地图上显示我的当前位置”?

其实它就像谷歌地图应用。当您打开谷歌地图时,蓝点会显示您当前的位置。您不需要第一次按“myLocationButton”。

所以这是代码:

import UIKit
import CoreLocation
import GoogleMaps

class GoogleMapsViewer: UIViewController {

    @IBOutlet weak var mapView: GMSMapView!

    let locationManager = CLLocationManager()
    let didFindMyLocation = false

    override func viewDidLoad() {
        super.viewDidLoad()

        let camera = GMSCameraPosition.cameraWithLatitude(23.931735,longitude: 121.082711, zoom: 7)
        let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)

        mapView.myLocationEnabled = true
        self.view = mapView

        // GOOGLE MAPS SDK: BORDER
        let mapInsets = UIEdgeInsets(top: 80.0, left: 0.0, bottom: 45.0, right: 0.0)
        mapView.padding = mapInsets

        locationManager.distanceFilter = 100
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()

        // GOOGLE MAPS SDK: COMPASS
        mapView.settings.compassButton = true

        // GOOGLE MAPS SDK: USER'S LOCATION
        mapView.myLocationEnabled = true
        mapView.settings.myLocationButton = true
    }
}


// MARK: - CLLocationManagerDelegate
extension GoogleMapsViewer: CLLocationManagerDelegate {

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        if status == .AuthorizedWhenInUse {
            locationManager.startUpdatingLocation()
            mapView.myLocationEnabled = true
            mapView.settings.myLocationButton = true
        }
    }
        func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.first {
            mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 20, bearing: 0, viewingAngle: 0)
            locationManager.stopUpdatingLocation()
        } 
    }
}

有人帮忙吗?非常感谢!

【问题讨论】:

  • 这足以显示当前位置 // GOOGLE MAPS SDK: COMPASS mapView.settings.compassButton = true // GOOGLE MAPS SDK: USER'S LOCATION mapView.myLocationEnabled = true mapView.settings.myLocationButton = true
  • 是的,显示当前位置就足够了。但是我可以在当前位置设置摄像头吗?

标签: ios swift google-maps


【解决方案1】:

Swift 3.x 解决方案,请查看Answer

首先你们必须在 Info.plist 文件中输入一个密钥 NSLocationWhenInUseUsageDescription

添加此密钥后,只需创建一个 CLLocationManager 变量并执行以下操作

@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()

}

当您运行代码时,您将弹出允许和不允许定位。只需点击允许,您就会看到您的当前位置。

确保在设备而不是模拟器上执行此操作。如果您使用的是模拟器,则必须选择一些自定义位置,然后才能看到蓝点。

【讨论】:

    【解决方案2】:

    使用此代码,

    你错过了addObserver方法和一些内容,

    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;
      });
    

    观察者法:

    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)
        }
    }
    

    希望对你有帮助

    【讨论】:

    • 我喜欢检查 oldValue 是否为 nil 的方法。
    • @iyyappan-ravi 有什么理由dispatch_async myLocationEnabled = YES?我已经在其他地方看到过这个,但我仍然不确定为什么需要这个。
    【解决方案3】:
    • 首先将以下内容添加到您的 info.plist

      1. NSLocationWhenInUseUsageDescription
      2. LSApplicationQueriesSchemes(数组类型并在此数组中添加两项 项目 0:谷歌浏览器, 第 1 项:comgooglemaps
    • 第二次转到https://developers.google.com/maps/documentation/ios-sdk/start 并按照步骤直到步骤5

    • 设置完所有内容后要做的最后一件事是转到您的 ViewController 并粘贴以下内容

      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)
              }
          }
      
      }
      

    (不要忘记在情节提要中添加一个视图并将其连接到 MapViw)

    现在您可以构建并运行以在 Google 地图上查看您当前的位置,就像您打开 Google 地图应用程序时一样

    享受编码:)

    【讨论】:

      【解决方案4】:

      Swift 3.0 或更高版本

      要在 GMS 地图视图中显示用户位置(蓝色标记),请确保您已获得位置权限并添加此行

      mapView.isMyLocationEnabled = true
      

      【讨论】:

        【解决方案5】:

        你可以使用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)
            }
        }
        

        【讨论】:

          【解决方案6】:

          SwiftUI

          struct GoogleMapView: UIViewRepresentable {
            @State var coordinator = Coordinator()
          
            func makeUIView(context _: Context) -> GMSMapView {
              let view = GMSMapView(frame: .zero)
              view.isMyLocationEnabled = true
              view.animate(toZoom: 18)
              view.addObserver(coordinator, forKeyPath: "myLocation", options: .new, context: nil)
            }
          
            func updateUIView(_ uiView: GMSMapView, context _: UIViewRepresentableContext<GoogleMapView>) {}
          
            func makeCoordinator() -> GoogleMapView.Coordinator {
              return coordinator
            }
          
            static func dismantleUIView(_ uiView: GMSMapView, coordinator: GoogleMapView.Coordinator) {
              uiView.removeObserver(coordinator, forKeyPath: "myLocation")
            }
          
            final class Coordinator: NSObject {
              override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
                if let location = change?[.newKey] as? CLLocation, let mapView = object as? GMSMapView {
                  mapView.animate(toLocation: location.coordinate)
                }
              }
            }
          }
          

          【讨论】:

            【解决方案7】:

            行后:

            view = mapView
            

            添加:

            mapView.isMyLocationEnabled = true
            

            这将启用您的位置:

            注意:- 模拟器上的位置是为特定位置预设的,您无法更改它们。如果要使用当前位置,则必须使用真实设备进行测试。

            【讨论】:

              【解决方案8】:
              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!!!!"
                                      }
                                  }
                              }
                          }
                      }
                  }
              

              【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-08-14
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多