web-dev-qa-db-ja.com

「ViewControllerを開いたときに、Googleマップに現在の場所を表示する」方法スイフトで?

IOS(Swift)のGoogleマップSDKを使用しています。

「ViewControllerを開いたときに、Googleマップに現在の場所を表示する」方法を知っている人はいますか?

実際、Google Maps Appと同じです。 Googleマップを開くと、青い点に現在地が表示されます。最初に「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()
        } 
    }
}

誰か助けて?どうもありがとうございます!

18
Eric Huang

Swift 3.xソリューションについては、これを確認してください Answer

まず、Info.plistファイルにキーを入力する必要がありますNSLocationWhenInUseUsageDescription

enter image description here

このキーを追加した後、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()

}

コードを実行すると、場所の許可と許可のポップアップが表示されます。 [許可]をクリックすると、現在の場所が表示されます。

これは、シミュレータではなくデバイスで行ってください。シミュレータを使用している場合は、カスタムの場所を選択する必要があります。そうすれば、あなただけが青い点を見ることができます。

enter image description here

34

このコードを使用して、

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

その役に立つことを願って

11
Iyyappan Ravi
  • 最初に以下をinfo.plistに追加します

    1. NSLocationWhenInUseUsageDescription
    2. LSApplicationQueriesSchemes(配列のタイプで、この配列に2つのアイテムを追加しますitem 0:googlechromes、item 1:comgooglemaps
  • 2番目の 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マップで現在の場所を確認するためにビルドして実行できます

コーディングをお楽しみください:)

3
Neen