利用swift和百度地圖寫一個定位返回位置的工具

importUIKit

classlocationTool:NSObject,BMKGeoCodeSearchDelegate,BMKLocationServiceDelegate{

classfuncsharelocationInstance() ->locationTool{

struct Singleton {

staticvarpredicate:dispatch_once_t=0

staticvarinstance:locationTool? =nil

}

dispatch_once(&Singleton.predicate, {

Singleton.instance =locationTool()

})

returnSingleton.instance!

}

varlocationService =BMKLocationService().then{

$0.allowsBackgroundLocationUpdates=true

//設定定位精度

$0.desiredAccuracy=kCLLocationAccuracyBest

}

vargeocodeSearch =BMKGeoCodeSearch()

funcsetUpDelegate() {

locationService.delegate=self

geocodeSearch.delegate=self

locationService.startUserLocationService()

}

deinit{

locationService.delegate=nil

geocodeSearch.delegate=nil

}

}

extensionlocationTool{

funcreverseGeoSearch(lat:CLLocationDegrees, lon:CLLocationDegrees){

letreverseGeocodeSearchOption =BMKReverseGeoCodeOption()

reverseGeocodeSearchOption.reverseGeoPoint=CLLocationCoordinate2DMake(lat, lon)

NSLog("%f,%f", lat,lon)

letflag =geocodeSearch.reverseGeoCode(reverseGeocodeSearchOption)

ifflag {

debugPrint("反geo檢索發送成功")

}else{

debugPrint("反geo檢索發送失敗")

locationService.startUserLocationService()

}

}

/**

*返回反地理編碼搜索結果

*@param searcher搜索對象

*@param result搜索結果

*@param error錯誤號,@see BMKSearchErrorCode

*/

funconGetReverseGeoCodeResult(searcher:BMKGeoCodeSearch!, result:BMKReverseGeoCodeResult!, errorCode error:BMKSearchErrorCode) {

debugPrint("onGetReverseGeoCodeResult error:\(error)")

iferror ==BMK_SEARCH_NO_ERROR{

letitem =BMKPointAnnotation()

item.coordinate= result.location

item.title= result.address

//??????????? postLocationGetCode(result.address)

cityAddress= result.address

letstring ="&province=\(result.addressDetail!.province)"+"&city=\(result.addressDetail!.city)"+"&area=\(result.addressDetail!.district)"

debugPrint(string)

HLNoteCenter.postNotificationName(HLNotificationAddressnotification, object: string)

locationService.stopUserLocationService()

}

}

funcwillStartLocatingUser() {

//??????? print("willStartLocatingUser")

debugPrint("willStartLocatingUser")

}

/**

*用戶方向更新后,會調用此函數

*@param userLocation新的用戶位置

*/

funcdidUpdateUserHeading(userLocation:BMKUserLocation!) {

debugPrint("heading is\(userLocation.heading)")

//??????? mapView!.updateLocationData(userLocation)

}

/**

*用戶位置更新后,會調用此函數

*@param userLocation新的用戶位置

*/

funcdidUpdateBMKUserLocation(userLocation:BMKUserLocation!) {

reverseGeoSearch(userLocation.location.coordinate.latitude, lon: userLocation.location.coordinate.longitude)

}

/**

*在地圖View停止定位后,會調用此函數

*@param mapView地圖View

*/

funcdidStopLocatingUser() {

debugPrint("didStopLocatingUser")

}

/**

*在地圖View停止失敗后,會調用此函數

*@param mapView地圖View

*/

funcdidFailToLocateUserWithError(error:NSError!) {

locationService.startUserLocationService()

}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容