美文网首页good地图开发相关
判断坐标点是否在范围内(高德Swift)

判断坐标点是否在范围内(高德Swift)

作者: 断忆残缘 | 来源:发表于2016-07-27 11:54 被阅读646次

    公司要做签到功能,稍稍研究了下高德的API写出下面一个类,以供大家使用。

    使用前准备:
      1.导入高德SDK,建议Cocoapods导入
    
      2.稍微做一些配置
        在info.plist 中配置NSLocationWhenInUseUsageDescription为
    YES
    
        <key>NSAppTransportSecurity</key>
        <dict>
            <key>NSAllowsArbitraryLoads</key>
            <true/>
        </dict>
    
      3.在桥接头中,导入以下两个头
        // 高德地图定位
        #import <AMapFoundationKit/AMapFoundationKit.h>
        #import <AMapLocationKit/AMapLocationKit.h>
    
    
    import UIKit
    
    typealias LocationJudgeCompletion = (isOnRegion: Bool?, formattedAddress: String?) -> Void
    
    class SingleLocaiton: NSObject {
      // 定位管理器
      private var locationManager: AMapLocationManager!
      // 定位完成
      private var completionBlock: AMapLocatingCompletionBlock?
      // 判断完成
      private var judgeCompletion: LocationJudgeCompletion?
      // 圆形区域半径(默认500)
      internal var radius: CLLocationDistance = 500
    
      override init() {
        super.init()
        locationManager = AMapLocationManager()
        locationManager.delegate = self
        // 设置精准度为百米
        locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
        // 单次定位超时时间
        locationManager.locationTimeout = 6
        // 单次定位逆地理超时时间
        locationManager.reGeocodeTimeout = 3
    
      }
      /**
       通过定位获取的地理坐标来判断,当前位置是否在某区域中
       - parameter coordinate:        参考位置坐标
       - parameter judgeCompletion:   判断完成回调
       */
      func locAndJudgeAction(coordinate: CLLocationCoordinate2D, judgeCompletion: LocationJudgeCompletion) {
        // 根据值设置区域
        let cirRegion = AMapLocationCircleRegion(center: coordinate, radius: radius, identifier: "circleRegion")
        locationManager.requestLocationWithReGeocode(true) { (location, regeocode, error) in
          if error != nil {
            print("locError:{\(error.code)-\(error.localizedDescription)}")
            if error.code == AMapLocationErrorCode.LocateFailed.rawValue {
              return
            }
          }
          var isOnRegion: Bool? = nil
          var formattedAddress: String? = nil
          if location != nil {
            isOnRegion = cirRegion.containsCoordinate(location.coordinate)
          }
          if regeocode != nil {
            formattedAddress = regeocode.formattedAddress
          }
          judgeCompletion(isOnRegion: isOnRegion, formattedAddress: formattedAddress)
        }
      }
    
      deinit {
        // 停止位置更新
        locationManager.stopUpdatingLocation()
        locationManager.delegate = nil
        print("deinit...")
      }
    }
    extension SingleLocaiton: AMapLocationManagerDelegate {
    
    }
    

    相关文章

      网友评论

        本文标题:判断坐标点是否在范围内(高德Swift)

        本文链接:https://www.haomeiwen.com/subject/sleojttx.html