日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

定位处理与地图

發布時間:2023/12/18 编程问答 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 定位处理与地图 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、定位處理

定位管理主要是通過GPS、蜂窩基站三角網、WiFi三種方式實現。

ios8系統下使用定位服務必須在info.plist中添加兩條變量:

分別用于描述程序始終使用和使用期間使用定位的說明。對應手機設置中定位服務中的始終和使用應用程序期間兩個選項。

1、在項目中引入框架CoreLoaction.framework。

2、創建一個定位服務管理類CLLocationManager來創建一個位置管理器,提供位置信息和高度信息,也可以監控進入和離開某個區域,還可以獲得設備的運行方向。遵循代理

CLLocationManagerDelegate。

//定義坐標坐標var currLocation : CLLocation! //創建位置管理器,用于定位服務管理類,它能夠給我們提供位置信息和高度信息,也可以監控設備進入或離開某個區域,還可以獲得設備的運行方向let locationManager : CLLocationManager = CLLocationManager() //指定代理locationManager.delegate = self//精確到1000米,距離過濾器,定義了設備移動后獲得位置信息的最小距離locationManager.distanceFilter = kCLLocationAccuracyBest//通過數字設置距離 // locationManager.distanceFilter = 200//發出授權申請//NSLocationAlwaysUsageDescription 和 NSLocationWhenInUseUsageDescription 。至于在plist添加的方法,就是在plist中添加一個鍵值對,然后把請求允許對應的Key值復制粘貼進去就可以了。value值是什么都可以,這個值會在請求允許的對話框中顯示出來給用戶看。總之是你自己定的。 locationManager.requestAlwaysAuthorization()//更新位置 locationManager.startUpdatingLocation()//更新方向 locationManager.startUpdatingHeading()print("定位開始")

通過didChangeAuthorizationStatus代理方法,可以獲得設備是否允許使用定位服務。

//代理方法--判斷是否可以使用定位服務 func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus){if status == CLAuthorizationStatus.NotDetermined || status == CLAuthorizationStatus.Denied{//允許使用定位服務//開始啟動定位服務更新 locationManager.startUpdatingLocation()//更新方向 locationManager.startUpdatingHeading()print("定位開始")}}

定位改變時委托會執行這個方法,通過定義一個CLLocation坐標對象來接收坐標值。

//距離改變就會收到該委托方法,獲取地理位置信息 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){//獲取最新坐標currLocation = locations.last//獲取經度longitudeTxt.text = "\(currLocation.coordinate.longitude)"//獲取緯度latitudeTxt.text = "\(currLocation.coordinate.latitude)"//獲取高度HeightTxt.text = "\(currLocation.altitude)"}

兩個坐標之間的距離可以通過func?distanceFromLocation(other:Double) ->Double方法得到:

//計算兩點之間距離let currentLocation = CLLocation(latitude: 53.204526, longitude: 50.111751)let targetLocation = CLLocation(latitude: 53.203715, longitude: 50.160374)let distance:CLLocationDistance = currentLocation.distanceFromLocation(targetLocation);print("兩點間距離是:\(distance)")

通過方法:func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading)可以獲取設備移動的方向,通過一組屬性提供航向讀數:

magneticHeading(磁場航向)和trueHeading(真實航向),如果航向為0.0,則前進方向為北;如果航向為90.0,則前進方向為東;如果航向為180.0,則前進方向為南;如果航向為270.0,則前進方向為西;只有打開定位服務才可以獲得真實航向。

代碼實現:

//獲取方向 func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading){headingLabel.text = "\(newHeading.trueHeading) degrees (true), \(newHeading.magneticHeading)degrees (magnetic)"print( headingLabel.text)}

定位出現錯誤時會調用下面的委托方法:

func locationManager(manager: CLLocationManager, didFailWithError error: NSError){print(error)if let clErr = CLError(rawValue: error.code){switch clErr {case .LocationUnknown:print("位置不明")case .Denied:print("允許檢索位置被拒絕")case .Network:print("用于檢索位置的網絡不可用")default:print("未知的位置錯誤")}} else {print("其他錯誤")let alert = UIAlertView(title: "提示信息", message: "定位失敗", delegate: nil, cancelButtonTitle: "確定")alert.show()}}

對于得到的定位信息我們需要把經緯度信息,反編碼成一個地址,這里需要用到CLGeocoder類來實現地理反編碼。

//地理信息反編碼 @IBAction func reverseGeocode(sender: AnyObject) {let geocoder = CLGeocoder()var p:CLPlacemark?geocoder.reverseGeocodeLocation(currLocation, completionHandler: { (placemarks, error) -> Void in// 強制 成 簡體中文let array = NSArray(object: "zh-hans")NSUserDefaults.standardUserDefaults().setObject(array, forKey: "AppleLanguages")// 顯示所有信息if error != nil {print("reverse geodcode fail: \(error!.localizedDescription)")return}let pm = placemarksif (pm!.count > 0){p = placemarks![0]print(p)//輸出反編碼信息 print("country = \(p?.country)")print("postalCode = \(p?.postalCode)")print("location = \(p?.location)")}else{print("No Placemarks!")}})} //地理信息編碼 @IBAction func locationBianMa (){//使用Google 服務進行地理編碼let geocoder = CLGeocoder()var p:CLPlacemark?geocoder.geocodeAddressString("北京海淀區北三環西路39號", completionHandler: { (placemarks, error) -> Void inif error != nil {print("reverse geodcode fail: \(error!.localizedDescription)")return}let pm = placemarksif (pm!.count > 0){p = placemarks![0]print("Longitude = \(p?.location!.coordinate.longitude)")print("Latitude = \(p?.location!.coordinate.latitude)")print(p)}else{print("No Placemarks!")}})}

二、地圖

通過MapKit可以把地圖嵌入到視圖中,MapKit框架主要提供了四個功能:顯示地圖、CLLocation和地址之間的轉換、支持在地圖上做標記、把一個位置解析成地址。

首先導入MapKit.framework框架,通過代碼或者靜態創建MKMapView對象,可以顯示地圖。

// MARK: - Map@IBOutlet var mainMapView: MKMapView!@IBAction func showMap() {//使用代碼創建地圖 // let mapView: MKMapView = MKMapView(frame: CGRectMake(0, 0, 320, 200)) // self.view.addSubview(mapView)//創建一個MKCoordinateSpan對象,設置地圖的范圍 越小越精確let latDelta = 0.05let longDelta = 0.05let currentLocationSpan: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)//定義一個區域,坐標使用定位獲取的當前坐標locationManager.location.coordinatelet currentRegion: MKCoordinateRegion = MKCoordinateRegionMake(locationManager.location!.coordinate, currentLocationSpan)//設置顯示區域self.mainMapView.setRegion(currentRegion, animated: true)//設置地圖顯示類型,標準地圖、衛星模式、混合模式。self.mainMapView.mapType = MKMapType.Standard //標準地圖//設置代理self.mainMapView.delegate = self//創建一個大頭針對象let objectAnnotation = MKPointAnnotation()//設置大頭針顯示位置,我們使用定位到的坐標objectAnnotation.coordinate = locationManager.location!.coordinate//設置點擊大頭針之后顯示的標題objectAnnotation.title = "北京海淀"//設置點擊大頭針之后顯示的描述objectAnnotation.subtitle = "北三環西路"//添加大頭針 self.mainMapView.addAnnotation(objectAnnotation)}

代理方法:

// MARK: - MKMapViewDelegate func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool){//地圖的縮放級別發生改變時, }func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool){//地圖的縮放完畢觸發 }func mapViewWillStartLoadingMap(mapView: MKMapView){//開始裝載地圖 }func mapViewDidFinishLoadingMap(mapView: MKMapView){//結束裝載地圖 }func mapViewDidFailLoadingMap(mapView: MKMapView, withError error: NSError){//裝載失敗 }func mapViewWillStartRenderingMap(mapView: MKMapView){//開始渲染下載的地圖塊時調用 }func mapViewDidFinishRenderingMap(mapView: MKMapView, fullyRendered: Bool){//渲染下載的地圖結束時調用 }//自定義大頭針樣式func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?{if annotation is MKUserLocation {//return nil so map view draws "blue dot" for standard user locationreturn nil}let reuseId = "pin"var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationViewif pinView == nil {//創建一個大頭針視圖pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)pinView!.canShowCallout = truepinView!.animatesDrop = true//設置大頭針顏色pinView!.pinColor = .Purple//設置大頭針點注釋視圖的右側按鈕樣式pinView!.rightCalloutAccessoryView = UIButton(type: UIButtonType.DetailDisclosure)}else {pinView!.annotation = annotation}return pinView}func mapView(mapView: MKMapView, didAddAnnotationViews views: [MKAnnotationView]){//添加注釋視圖 }func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl){}func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView){//點擊大頭針注釋視圖 }func mapView(mapView: MKMapView, didDeselectAnnotationView view: MKAnnotationView){//取消點擊大頭針注釋視圖 }func mapViewWillStartLocatingUser(mapView: MKMapView){//正在跟蹤用戶的位置 }func mapViewDidStopLocatingUser(mapView: MKMapView){//停止跟蹤用戶的位置 }func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation){//更新用戶的位置 }func mapView(mapView: MKMapView, didFailToLocateUserWithError error: NSError){//跟蹤用戶的位置 失敗 }func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, didChangeDragState newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState){//移動annotation位置時調用。newState為宏,表示幾個狀態。是否能移動位置在annotation中設置。 }func mapView(mapView: MKMapView, didChangeUserTrackingMode mode: MKUserTrackingMode, animated: Bool){//改變UserTrackingMode }func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer{//設置overlay的渲染return MKOverlayRenderer()}func mapView(mapView: MKMapView, didAddOverlayRenderers renderers: [MKOverlayRenderer]){//地圖上加上了overlayRenderers后調用}

?

轉載于:https://www.cnblogs.com/fengmin/p/5718414.html

總結

以上是生活随笔為你收集整理的定位处理与地图的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。