Swift-integrated with Baidu map's perimeter radar function

Source: Internet
Author: User
Tags string format uikit radar

I. Introduction of peripheral radar function

1, what is the perimeter radar

(1) The peripheral radar function is a set of SDK functional interfaces for mobile-end developers (synchronous support for Android and IOS side).
(2) The surrounding radar is an intermediary service between the front-end SDK products and the back-end lbs cloud, which connects Baidu lbs open platform.


2, use the scene

Using the peripheral radar function, we can easily in their own applications, to help users to find the surrounding with "I" Use the same app people. Like what:
(1) Look around who and "I" Use the same App, where is the distribution?
(2) to see what the surrounding users listen to songs, what articles to see, what new dynamic?
(3) What is the latest news and information about the surrounding area?


Ii. preparatory work

1, Application API Key
First we have to go to the Baidu Map open platform to apply for an API Key, for our program use. A specific reference to my previous article: Swift-Baidu Map SDK Configuration and use (with examples)

2, registered perimeter radar
To use the perimeter radar function, we are not enough to apply for an API Key. This key is also required to register the operation.
The registered perimeter radar is the basis for using its corresponding function. Registration enables the binding of relationships between one or more applications to enable the viewing of location information between each other.


3, Integrated SDK

The surrounding radar is a function module of the SDK product of Baidu map. In addition to the Baidu Map SDK to integrate the basic package, but also to integrate the surrounding radar related library (baidumapapi_radar.framework). The concrete integration method also refers to the preceding article.

Also in the bridge header file import the radar library file.

#import <BaiduMapAPI_Base/BMKBaseComponent.h>//introduction of Base-related all header files
#import <BaiduMapAPI_Map/BMKMapComponent.h>//Map features all header files
#import <BaiduMapAPI_Map/BMKMapView.h>//Only the required single-head file X is introduced
#import <BaiduMapAPI_Radar/BMKRadarComponent.h>//introduction of peripheral radar function All header files
/****** The following few temporarily do not need ******/
#import <BaiduMapAPI_Search/BMKSearchComponent.h>//introduction of Retrieval function All header files
#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h>//introduction of cloud Retrieval function All header files
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//introduction of positioning function All header files
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>//Introduction of computing Tools All header files

Iii. Introduction to sample examples

The following example demonstrates the use of a perimeter radar by using a "nearby person" sample.
(1) After the program is started, the application will automatically upload the user location information (every 5 seconds)
(2) Upload the location of the time we also have the upload user name (randomly generated)
(3) The main interface has a "nearby people" list, showing the other users within 500 meters and the distance from you (the list is also 5 seconds refresh once).
(4) Only use a mobile phone is not very good-looking effect. Take two or more cell phone tests to see other people's information and how far they are from you. For example, I use 3 mobile phones to test, of which 1 of the operating effect of the phone is as follows:


Four, sample code

1,info.plist
Since we want to use corelocation to get real-time location data, we add a location description in Info.plist (or null value):
Nslocationwheninusedescription: Allows you to get GPS descriptions in the foreground
Nslocationalwaysusagedescription: Allows the GPS description to be obtained in the background


2,appdelegate.swift

Use the authorization Key we previously requested to declare and initialize the 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 ()
If you want to focus on network and authorization validation events, set Generaldelegate parameters
Let ret = _mapmanager? Start ("Mrytrhzazult5aojf5tmsxxxxxxxxxxx",
Generaldelegate:self)
if ret = = False {
NSLog ("Manager start failed!")
}
return True
}
//...............

3,viewcontroller.swift

Location information upload, the location of the surrounding search and display functions are implemented here. Notice here that we need to set the UserID before uploading and getting the location information.
This will also be generated automatically if we do not set it. The automatically generated userid is unique and related to the current device. This means that the generated userid are the same for each device that starts the program. (So shutting down the startup program multiple times does not cause problems with new users)


Import Uikit
Import Corelocation

Class Viewcontroller:uiviewcontroller, Cllocationmanagerdelegate, Bmkradarmanagerdelegate,
Uitableviewdelegate, Uitableviewdatasource {

Location Manager
Let Locationmanager:cllocationmanager = Cllocationmanager ()

Current position coordinates
var currcoordinate:cllocationcoordinate2d?

Peripheral Radar Management Class
var _radarmanager:bmkradarmanager?

Timer, for timing request peripheral Information data
var timer:nstimer!

Peripheral User Collection
var infolist:[bmkradarnearbyinfo] = [Bmkradarnearbyinfo] ()

Display table for peripheral users
var tableview:uitableview?

Current user name
var username:string!

Override Func Viewdidload () {
Super.viewdidload ()

Randomly generate a user name
UserName = "Stranger \" (String format:%03i, Int (Arc4random ()%1000)) "
Self.title = "\ (userName), Hello! Here are the people around you. "

To set the Location Service Manager agent
Locationmanager.delegate = Self
Set positioning progress
Locationmanager.desiredaccuracy = Kcllocationaccuracybest
Update distance
Locationmanager.distancefilter = 100
Send an Authorization request
Locationmanager.requestalwaysauthorization ()
if (cllocationmanager.locationservicesenabled ()) {
Open Location Service Update If you are allowed to use location services
Locationmanager.startupdatinglocation ()
Print ("Locate start")
}

Get the example of peripheral radar management class
_radarmanager = Bmkradarmanager.getradarmanagerinstance ()
Before uploading and pulling position information, you need to set UserID, or you will automatically generate
_radarmanager? UserId = "u007"
By adding radar delegate to obtain the location information of the automatic uploading and obtaining the results of the radar operation
_radarmanager? Addradarmanagerdelegate (self)

Position information automatically uploaded continuously (upload every 5 seconds)
_radarmanager? Startautoupload (5)
Enable timer, control every 5 seconds to execute Requestnearbydata method, request peripheral information
Timer = Nstimer.scheduledtimerwithtimeinterval (5,
Target:self,selector: #selector (Viewcontroller.requestnearbydata),
Userinfo:nil,repeats:true)

Create a table view
Self.tableview = UITableView (Frame:self.view.frame, Style:UITableViewStyle.Plain)
self.tableview!. delegate = Self
self.tableview!. DataSource = Self
To create a reused cell
self.tableview!. RegisterClass (Uitableviewcell.self,
Forcellreuseidentifier: "Swiftcell")
Self.view.addSubview (self.tableview!)
}

Position change execution to get new location, old location
Func Locationmanager (Manager:cllocationmanager,
Didupdatelocations locations: [Cllocation]) {
Get the latest coordinates
Currcoordinate = locations.last!. Coordinate
}

Get my location information (automatic upload call)
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
}
}

Return to Radar upload results
Func Ongetradaruploadresult (Error:bmkradarerrorcode) {
If error = = Bmk_radar_no_error {
Print ("position upload succeeded")
}else{
Print ("position upload failed")
}
}

Initiate a retrieval request to get perimeter information
Func Requestnearbydata () {
If let Centerpt = currcoordinate {
Let option = Bmkradarnearbysearchoption ()
Option.radius = 500//Search Radius
Option.sorttype = Bmk_radar_sort_type_distance_from_near_to_far//Sort Way
OPTION.CENTERPT = CENTERPT//Retrieval Center Point
Initiate a search

Let res = _radarmanager?. Getradarnearbysearchrequest (option)
If res! {
Print ("Peripheral information gets successful")
} else {
Print ("Peripheral information gets failed")
}
}
}

Get to perimeter location information callback
Func Ongetradarnearbysearchresult (result:bmkradarnearbyresult!, Error:bmkradarerrorcode) {
If error = = Bmk_radar_no_error {
Print ("Number of users around:", Result.totalnum)
Self.infolist = Result.infolist as! [Bmkradarnearbyinfo]
Self.tableview? Reloaddata ()
}
}

In this case, there is only one partition
Func Numberofsectionsintableview (Tableview:uitableview)-> Int {
return 1;
}

Returns the number of table rows (that is, returns the number of controls)
Func TableView (Tableview:uitableview, numberofrowsinsection section:int)-> Int {
Return Self.infoList.count
}

Create each cell display (create a parameter indexpath a specified cell)
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 ()
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.