是否可以获取经纬度表单mapKit并在Google Map中使用它?

时间:2018-10-16 08:37:17

标签: swift xcode

只说标题就好 代码:

import UIKit
import MapKit
import CoreLocation
import GoogleMaps

class onlyMapVC: UIViewController {


    @IBOutlet weak var theMap: GMSMapView!
    //    @IBOutlet weak var upperView: UIView!

 var currentLat = 0.0
var currentLong = 0.0



override func viewDidLoad() {
    super.viewDidLoad()

    theMap.delegate = self


    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()


        currentLat = (locationManager.location?.coordinate.longitude)!
        currentLong = (locationManager.location?.coordinate.longitude)!


        let coordinates = CLLocationCoordinate2D(latitude: currentLat, longitude: currentLong)
                  marker.map = theMap

        self.theMap.camera = GMSCameraPosition(target: coordinates, zoom: 6.0, bearing: 0, viewingAngle: 0)


    }

但是结果不正确,这表明我在远离当前位置的任何地方有帮助吗?

我正在使用Xcode 10 swift 4

2 个答案:

答案 0 :(得分:1)

您同时将currentLat和currentLong设置为经度:

currentLat = (locationManager.location?.coordinate.longitude)!
currentLong = (locationManager.location?.coordinate.longitude)!

应该是:

currentLat = (locationManager.location?.coordinate.latitude)!
currentLong = (locationManager.location?.coordinate.longitude)!

答案 1 :(得分:0)

请参阅documentation,您应该通过委托方法locationManager(_:didUpdateLocations:)接收位置更新。

  

startUpdatingLocation()

     

此方法立即返回。调用此方法会使位置管理器获得初始位置修复(可能需要几秒钟),并通过调用其locationManager(_:didUpdateLocations :)方法来通知您的委托。之后,接收者主要在超过distanceFilter属性中的值时生成更新事件。但是,在其他情况下也可能会提供更新。例如,如果硬件收集到更准确的位置读数,则接收方可能会发送另一条通知。

因此,您应该调用startUpdatingLocation,并在收到GPS位置后等待调用委托方法。

所以尝试这样的事情:

class onlyMapVC: UIViewController, CLLocationManagerDelegate {

    @IBOutlet weak var theMap: GMSMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        theMap.delegate = self

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, 
           didUpdateLocations locations: [CLLocation]) {
        let currentLocation = locations.first?.coordinate
        marker.map = theMap

        self.theMap.camera = GMSCameraPosition(target: currentLocation, zoom: 6.0, bearing: 0, viewingAngle: 0)

    }
}

确保您的UIViewController具有协议CLLocationManagerDelegate