您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

Swift 實戰:集成百度地圖的周邊雷達功能

編輯:iOS 7 技巧

下面來看一篇關於 Swift 集成百度地圖周邊雷達功能的示例,希望這篇文章能幫助到各位朋友,具體細節如下文所述。

一、周邊雷達功能介紹

1,什麼是周邊雷達
(1)周邊雷達功能,是面向移動端開發者的一組 SDK 功能接口(同步支援 Android 和 iOS 端)。
(2)周邊雷達本質上是一個連接百度 LBS 開放平台前端 SDK 產品和後端 LBS 雲的中間服務。

2,使用場景
借助周邊雷達,我們可以便捷地在自己的應用裡幫用戶查找周邊「和我」使用同一款 App 的人。比如:
(1)查看周邊有哪些人跟「我」使用同一個 App,分佈在哪裡?
(2)查看周邊用戶在聽什麼歌、看什麼文章、有什麼新動態?
(3)查看周邊有什麼最新發生的新聞、資訊?

二、準備工作

1,申請 API Key
首先我們要到百度地圖開放平台上申請一個 API Key,供程序使用。

2,注冊周邊雷達
要使用周邊雷達,光申請一個 API Key 還不夠,還需要對這個 Key 做相應的注冊操作。注冊周邊雷達是使用其功能的前提,通過注冊可實現一個或多個應用之間的關係綁定,實現相互之間的位置信息查看。

3,集成 SDK
周邊雷達是百度地圖 SDK 產品的一個功能模塊。我們除了要集成百度地圖 SDK 的基礎包外,還要集成周邊雷達相關庫(BaiduMapAPI_Radar.framework)。同時,橋接頭文件中也要把雷達庫文件 import 進來:

#import <BaiduMapAPI_Base/BMKBaseComponent.h> //引入base相關所有的頭文件
#import <BaiduMapAPI_Map/BMKMapComponent.h> //引入地圖功能所有的頭文件
#import <BaiduMapAPI_Map/BMKMapView.h> //只引入所需的單個頭文件
#import <BaiduMapAPI_Radar/BMKRadarComponent.h> //引入周邊雷達功能所有的頭文件
/****** 下面的幾個暫時不需要 ******/
//#import <BaiduMapAPI_Search/BMKSearchComponent.h> //引入檢索功能所有的頭文件
//#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h> //引入雲檢索功能所有的頭文件
//#import <BaiduMapAPI_Location/BMKLocationComponent.h> //引入定位功能所有的頭文件
//#import <BaiduMapAPI_Utils/BMKUtilsComponent.h> //引入計算工具所有的頭文件

三、示例介紹

下面通過「附近的人」這個小示例演示周邊雷達的用法。
(1)程序啟動後,應用會自動定時上傳用戶位置信息(每隔 5 秒)。
(2)上傳位置時,我們同時附帶上傳用戶名(隨機生成)。
(3)主界面有個「附近的人」列表,顯示 500 米範圍內的其他用戶,以及離你的距離(列表同樣每 5 秒刷新一次)。
(4)只用一台手機不太好看出效果,拿兩台或以上數量的手機測試,就能看到其他人的信息及他們離你的距離。

四、示例代碼

1,info.plist
由於我們要用 CoreLocation 獲取實時位置數據,所以在 info.plist 中加入定位描述(Value 值為空也可以):
NSLocationWhenInUseDescription:允許在前台獲取 GPS 的描述
NSLocationAlwaysUsageDescription:允許在後台獲取 GPS 的描述

2,AppDelegate.swift
在這裡使用我們之前申請的授權 Key,來對 BMKMapManager 進行聲明和初始化。

import UIKit
 
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, BMKGeneralDelegate {
 
    var window: UIWindow?
    
    var _mapManager: BMKMapManager?
 
    func application(application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
         
        _mapManager = BMKMapManager()
        // 如果要關注網絡及授權驗證事件,請設定generalDelegate參數
        let ret = _mapManager?.start("mRYTrHzAZUlT5Aojf5tMSxxxxxxxxxxx",
                                     generalDelegate: self)
        if ret == false {
             NSLog("manager start failed!")
        }
        return true
    }
    //...............

3,ViewController.swift
位置信息上傳、周邊位置檢索並顯示等功能都在這裡實現。這裡要留意的是,在上傳和獲取位置信息前,我們需要設置 userid;若不設置,系統也會自動生成。自動生成的 userid 是唯一的,且與當前設備相關——也就是說,同一設備每次啟動程序後生成的 userid 都一樣(因此反覆關閉啟動程序不會不斷新增用戶)。

import UIKit
import CoreLocation
 
class ViewController: UIViewController, CLLocationManagerDelegate, BMKRadarManagerDelegate,
        UITableViewDelegate, UITableViewDataSource {
    
    //定位管理器
    let locationManager:CLLocationManager = CLLocationManager()
    
    //當前位置坐標
    var currCoordinate:CLLocationCoordinate2D?
 
    //周邊雷達管理類
    var _radarManager:BMKRadarManager?
    
    //定時器,用於定時請求周邊信息數據
    var timer:NSTimer!
    
    //周邊用戶集合
    var infoList:[BMKRadarNearbyInfo] = [BMKRadarNearbyInfo]()
    
    //顯示周邊用戶的表格
    var tableView:UITableView?
    
    //當前用戶名稱
    var userName:String!
    
    override func viewDidLoad() {
        super.viewDidLoad()
         
        //隨機生成一個用戶名
        userName = "陌生人\(String(format: "%03i", Int(arc4random()%1000)))"
        self.title = "\(userName),你好!下面是你周圍的人。"
         
        //設置定位服務管理器代理
        locationManager.delegate = self
        //設置定位精度
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        //更新距離
        locationManager.distanceFilter = 100
        //發送授權申請
        locationManager.requestAlwaysAuthorization()
        if (CLLocationManager.locationServicesEnabled()){
            //允許使用定位服務的話,開啟定位服務更新
            locationManager.startUpdatingLocation()
            print("定位開始")
        }
 
        //獲取周邊雷達管理類實例
        _radarManager =  BMKRadarManager.getRadarManagerInstance()
        //在上傳和拉取位置信息前,需要設置userid,否則會自動生成
        //_radarManager?.userId = "u007"
        //通過添加radar delegate獲取自動上傳時的位置信息,以及獲得雷達操作結果
        _radarManager?.addRadarManagerDelegate(self)
         
        //位置信息連續自動上傳(每隔5秒上傳一次)
        _radarManager?.startAutoUpload(5)
        //啟用計時器,控制每5秒執行一次requestNearbyData方法,請求周邊信息
        timer = NSTimer.scheduledTimerWithTimeInterval(5,
                        target:self,selector:#selector(ViewController.requestNearbyData),
                        userInfo:nil,repeats:true)
         
        //創建表視圖
        self.tableView = UITableView(frame: self.view.frame, style:UITableViewStyle.Plain)
        self.tableView!.delegate = self
        self.tableView!.dataSource = self
        //創建一個重用的單元格
        self.tableView!.registerClass(UITableViewCell.self,
                                     forCellReuseIdentifier: "SwiftCell")
        self.view.addSubview(self.tableView!)
    }
    
    //定位改變執行,可以得到新位置、舊位置
    func locationManager(manager: CLLocationManager,
                         didUpdateLocations locations: [CLLocation]) {
        //獲取最新的坐標
        currCoordinate = locations.last!.coordinate
    }
    
    //獲取我的位置信息(自動上傳調用)
    func getRadarAutoUploadInfo() -> BMKRadarUploadInfo! {
        if let pt = currCoordinate{
            let myinfo = BMKRadarUploadInfo()
            myinfo.extInfo = userName
            //myinfo.pt = CLLocationCoordinate2DMake(39.916, 116.404)
            myinfo.pt = pt
            return myinfo
        }else{
            return nil
        }
    }
    
    //返回雷達 上傳結果
    func onGetRadarUploadResult(error: BMKRadarErrorCode) {
        if error == BMK_RADAR_NO_ERROR {
            print("位置上傳成功")
        }else{
            print("位置上傳失敗")
        }
    }
    
    //發起檢索請求,獲取周邊信息
    func requestNearbyData() {
        if let centerPt = currCoordinate {
            let option =  BMKRadarNearbySearchOption()
            option.radius = 500 //檢索半徑
            option.sortType = BMK_RADAR_SORT_TYPE_DISTANCE_FROM_NEAR_TO_FAR //排序方式
            option.centerPt = centerPt //檢索中心點
            //發起檢索
            
            let res = _radarManager?.getRadarNearbySearchRequest(option)
            if res! {
                print("周邊信息獲取成功")
            } else {
                print("周邊信息獲取失敗")
            }
        }
    }
    
    //獲取到周邊位置信息回調
    func onGetRadarNearbySearchResult(result: BMKRadarNearbyResult!, error: BMKRadarErrorCode) {
        if error == BMK_RADAR_NO_ERROR {
            print("周邊用戶數量:",result.totalNum)
            self.infoList = result.infoList as! [BMKRadarNearbyInfo]
            self.tableView?.reloadData()
    }
    }
    
    //在本例中,只有一個分區
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1;
    }
    
    //返回表格行數(也就是返回控件數)
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.infoList.count
    }
    
    //創建各單元顯示內容(創建參數indexPath指定的單元)
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
        -> UITableViewCell {
        let cell =  UITableViewCell(style: UITableViewCellStyle.Value1,
                  reuseIdentifier: "SwiftCell")
        cell.textLabel?.text = self.infoList[indexPath.row].extInfo
        cell.detailTextLabel?.text = "\(self.infoList[indexPath.row].distance)m"
        return cell
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved