swift使用谷歌地图实现定位

swift使用谷歌地图实现定位


  • 在国内app中虽然使用Google map的比较少,但在一些应用中需要获取国外的地址之类的往往就需要使用到
    谷歌地图,例如携程旅行中就有用到。下面主要是介绍使用谷歌地图定位的用法,具体的方法可以参考这里
    下面的方法也是参考这篇文章来写的,只是就里面的一些代码的swift版本的原因做的一些就自己的swift版本

的修改,下面使用的是swift2.3

首先要实现定位的功能之前要先定义如下属性:

var mapView : GMSMapView!
var locationManager = CLLocationManager()
var didFindMyLocation = false  //只是用来做一个标记

然后再ViewDidLoad()中:

mapView = GMSMapView()  //初始化地图,注意这一步非常的重要
locationManager.desiredAccuracy = KCLLocationAccuracyHundredMeters  //定位精度
locationManager.destanceFilter = 50  //指定最小距离更新
locationManager.delegate = self  //遵循CLLocationManagerDelegate代理
locationManager.requestWhenInUseAutherization()
//设置监听来监听位置的变化
mapView.addObserver(self, forKeyPath:"myLocation", options:NSKeyValueObservingOptions.New, context:nil)

代理方法

//谷歌地图开始定位
func locationManager(manager:CLLocationManager!, didChangeAutherizationStatus status:CLAuthorizationStatus){
    if status == CLAuthorizationStatus.AuthorizaedWhenInUse{
        self.mapView.myLocationEnabled = true  //开始定位
    }
}
//监听处理位置坐标更新
Override func observerValueForKeyPath(keyPath:String?, ofObject object:AnyObject?,
change:[String:AnyObject]?, Context:UnSafeMutablePointer<Void>){
    if !didFindMyLocation{
        let myLocation:CLLocation = Change![NSKeyValueChangeNewKey] as! CLLocation
        self.mapView.camera = GMSCameraPosition.cameraWithTarget(myLocation.coordinate, zoom:10.0)
        self.mapView.settings.myLocationButton = true
        didFindMyLocation = true
        print("latitude-->\(myLocation.coordinate.latitude) longitude-->\(myLocation.coordinate.longitude)")
    }
    self.mapView.removeObserver(self, forKeyPath:"myLocation") //最后要记住一定要移除观察者,不然当程序返回上一个页面时会闪退
}

猜你喜欢

转载自blog.csdn.net/qq_37269542/article/details/54743496