ios 如何“当我打开 ViewController 时,在谷歌地图上显示我当前的位置?” 在斯威夫特?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38626649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:46:53  来源:igfitidea点击:

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

iosswiftgoogle-maps

提问by Eric Huang

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

我正在使用 iOS(Swift)的谷歌地图 sdk。

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

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

Actually it just like Google Maps App. When you open the Google Maps, the blue spot will show your current location. You don't need press the "myLocationButton" in first time.

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

So this is the code:

所以这是代码:

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

Anyone help? Thank you so much!

有人帮忙吗?非常感谢!

回答by Rajan Maheshwari

For Swift 3.xsolution, please check this Answer

对于Swift 3.x解决方案,请检查此答案

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

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

enter image description here

在此处输入图片说明

After adding this key just make a CLLocationManagervariable and do the following

添加此键后,只需创建一个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()

}

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 devicerather 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.

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

enter image description here

在此处输入图片说明

回答by Iyyappan Ravi

Use this code,

使用此代码,

You miss the addObservermethod and some content,

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

viewDidLoad:

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

希望它有帮助

回答by Neen

  • 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/startand 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)
            }
        }
    
    }
    
  • 首先将以下内容添加到您的 info.plist

    1. NSLocationWhenInUseUsageDescription
    2. LSApplicationQueriesSchemes(数组类型,并在此数组中添加两个项目项目 0 : googlechromes ,项目 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)
            }
        }
    
    }
    

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

(不要忘记在故事板中添加一个视图并将其连接到 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

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

enjoy coding :)

享受编码:)

回答by Antony Wong

You can use RxCoreLocation:

您可以使用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 = 
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)
      }
    }
  }
}
.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) } }

回答by susemi99

SwiftUI

用户界面

mapView.isMyLocationEnabled = true

回答by BharathRao

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

Swift 3.0 或更高版本

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

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!!!!"
                        }
                    }
                }
            }
        }
    }

回答by Nandhu

##代码##