ios百度地图的使用示例
协议
#ifndef NavLeftBtnDelegate_h
#define NavLeftBtnDelegate_h
@protocol NavLeftDelegateSet <NSObject>
- (void)setlocationBtn:(UIBarButtonItem *)barButtonItem;
- (void)setSearchBtn:(UIBarButtonItem *)barButtonItem;
@end
#endif /* NavLeftBtnDelegate_h */
Controller文件
#import "NavLeftBtnDelegate.h"
@interface NearByGasStationViewController : BaseViewController
@property (nonatomic, assign) id<NavLeftDelegateSet> delegate;
@end
//
// NearByGasStationViewController.m
#import "NearByGasStationViewController.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件
#import <BaiduMapAPI_Search/BMKSearchComponent.h>//引入检索功能所有的头文件
#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h>//引入云检索功能所有的头文件
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>//引入计算工具所有的头文件
#import <BaiduMapAPI_Radar/BMKRadarComponent.h>//引入周边雷达功能所有的头文件
#import <BaiduMapAPI_Map/BMKMapView.h>//只引入所需的单个头文件
#import <JZLocationConverter/JZLocationConverter.h>//坐标转换
#import "POIAnnotation.h"
#import "LivePoiTableView.h"
#import "LivePoiCell.h"
#import "LivePoiSectionHeader.h"
#import "JXLayoutButton.h"
#import "StrUtil.h"
typedef NS_ENUM(NSInteger, TVMapType){
TVMapTypebaidumap,
TVMapTypeiosamap,
TVMapTypecomgoolemaps,
TVMapTypeqqmap,
TVMapTypeapple
};
@interface NearByGasStationViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate,BMKPoiSearchDelegate,BMKGeoCodeSearchDelegate,LivePoiCellDelegate,LivePoiSectionHeaderDelegate>{
CGFloat _beginOffsetY; // 起始Y轴偏移量
NSInteger curPage;
}
@property (nonatomic, strong) BMKMapView *mapView;
@property (nonatomic, strong) BMKLocationService* locService;
//检索
@property (nonatomic, strong) BMKPoiSearch* poiSearch;
@property (nonatomic, strong) BMKGeoCodeSearch* geoCodeSearch;
@property (nonatomic, assign) CLLocationCoordinate2D locationcoord2d;
/**
定位按钮
*/
@property (nonatomic, weak) UIButton *locateButton;
@property (nonatomic, strong) JXLayoutButton *leftBtn;
/**
表视图
*/
@property (nonatomic, weak) LivePoiTableView *tableView;
/**
更多按钮
*/
@property (nonatomic, weak) UIButton *moreButton;
/**
搜索视图
*/
@property (nonatomic, weak) UIView *searchView;
/**
城市
*/
@property (nonatomic, copy) NSString *city;
@property (nonatomic, copy) NSString *province;
@property (nonatomic, copy) NSString *address;
/**
位置
*/
@property (nonatomic, assign) CLLocationCoordinate2D location;
/**
poi数组
*/
@property (nonatomic, strong) NSMutableArray <POIAnnotation *> *poiAnnotations;
/**
筛选poi数组
*/
@property (nonatomic, copy) NSArray *sortedAnnotations;
/**
筛选类型
*/
@property (nonatomic, assign) TVPOIType sortType;
@end
@implementation NearByGasStationViewController
static NSString *const kLivePoiSectionHeaderID = @"LivePoiSectionHeader";
static NSString *const kLivePoiCellID = @"LivePoiCell";
#pragma mark - 导航栏
#pragma mark - 定制导航条内容
- (void) customNavItem {
_leftBtn = [self generateButtonWithStyle:JXLayoutButtonStyleLeftImageRightTitle leftImageNormalName:icon_PositionNormal leftImageSelectName:icon_PositionSelected rightTitle:[StrUtil isBlankString:self.city]?@"北京":self.city];
[_leftBtn sizeToFit];
_leftBtn.left = 20.0;
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_leftBtn];
if ([self.delegate respondsToSelector:@selector(setlocationBtn:)]) {
[self.delegate setlocationBtn:self.navigationItem.leftBarButtonItem];
}
UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
[searchButton setImage:[UIImage imageNamed:@"live_search"] forState:UIControlStateNormal];
[searchButton setTitle:@"搜索" forState:UIControlStateNormal];
#pragma mark Action - 搜索
@weakify(self)
[[searchButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
@strongify(self);
self.searchView.hidden = NO;
}];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:searchButton];
if ([self.delegate respondsToSelector:@selector(setSearchBtn:)]) {
[self.delegate setSearchBtn:self.navigationItem.rightBarButtonItem];
}
[searchButton sizeToFit];
}
- (void)rightAction{
self.searchView.backgroundColor = [UIColor whiteColor];
}
//定位按钮
- (JXLayoutButton *)generateButtonWithStyle:(JXLayoutButtonStyle)style leftImageNormalName:(NSString *)leftImage leftImageSelectName:(NSString *)leftSelectImage rightTitle:(NSString *)title{
JXLayoutButton *button = [JXLayoutButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:leftImage] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:leftSelectImage] forState:UIControlStateSelected];
[button setTitle:title forState:UIControlStateNormal];
[button setTitleColor:kGrayTextColor forState:UIControlStateNormal];
[button setTitleColor:kThemeColor forState:UIControlStateSelected];
[button setTintColor:kThemeColor];
button.layoutStyle = style;
return button;
}
- (UIStatusBarStyle)preferredStatusBarStyle {
return UIStatusBarStyleLightContent;
}
#pragma mark - LifeCircle
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self setNeedsStatusBarAppearanceUpdate];
[self customNavItem];
curPage = 0;
[_mapView viewWillAppear];
_mapView.delegate = self;
_locService.delegate = self;
_geoCodeSearch.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[_mapView viewWillDisappear];
_mapView.delegate = nil;
_locService.delegate = nil;
_geoCodeSearch.delegate = nil;
[self.view endEditing:YES];
}
- (void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
if (_poiSearch != nil) {
_poiSearch = nil;
}
if (_mapView) {
_mapView = nil;
}
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = kBgColor;
self.title = @"加油站";
[self createUI];
self.mapView.backgroundColor = kBgColor;
self.tableView.backgroundColor = [UIColor clearColor];
[self performSelector:@selector(locate) withObject:nil afterDelay:0.1];
}
- (void)applicationWillResignActive:(UIApplication *)application {
//程序将要进入后台
[BMKMapView willBackGround];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
//程序进入前台
[BMKMapView didForeGround];
}
#pragma mark - createUI
- (void)createUI{
UIButton *locateButton = [UIButton buttonWithType:UIButtonTypeCustom];
// _locateButton = locateButton;
// locateButton.titleLabel.font = [UIFont systemFontOfSize:14];
// [locateButton setTitleColor:kLightGrayColor forState:UIControlStateNormal];
// [locateButton setTitle:@"所在位置" forState:UIControlStateNormal];
// [locateButton setImage:[UIImage imageNamed:@"live_location"] forState:UIControlStateNormal];
// locateButton.titleEdgeInsets = UIEdgeInsetsMake(0, 2, 0, 0);
// locateButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//#pragma mark Action - 定位
// [[locateButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(UIButton *x) {
// @strongify(self);
// [self locate];
// }];
}
- (BMKMapView *)mapView{
if (!_mapView) {
_mapView = [[BMKMapView alloc] init];
[_mapView setZoomLevel:13];
_mapView.isSelectedAnnotationViewFront = YES;
_mapView.width = kScreenWidth;
_mapView.height = self.view.frame.size.height;//kScreenHeight;
_mapView.delegate = self;
_mapView.showsUserLocation = YES;
_mapView.userTrackingMode = BMKUserTrackingModeFollow;
[self.view insertSubview:_mapView atIndex:0];
}
return _mapView;
}
#pragma mark -tableView懒加载
- (UITableView *)tableView{
if (!_tableView) {
LivePoiTableView *tableView = [[LivePoiTableView alloc] initWithFrame:self.mapView.frame style:UITableViewStylePlain];
_tableView = tableView;
tableView.dataSource = self;
tableView.delegate = self;
tableView.backgroundColor = [UIColor clearColor];
tableView.layoutMargins = UIEdgeInsetsZero;
tableView.separatorInset = UIEdgeInsetsZero;
tableView.rowHeight = 56.0;
[tableView registerClass:[LivePoiCell class] forCellReuseIdentifier:kLivePoiCellID];
[tableView registerClass:[LivePoiSectionHeader class] forHeaderFooterViewReuseIdentifier:kLivePoiSectionHeaderID];
[tableView.panGestureRecognizer addTarget:self action:@selector(handlePan:)];
[self.view insertSubview:tableView aboveSubview:self.mapView];
}
return _tableView;
}
- (UIButton *)moreButton{
if (!_moreButton) {
UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
_moreButton = moreButton;
moreButton.backgroundColor = [UIColor whiteColor];
moreButton.titleLabel.font = [UIFont systemFontOfSize:16];
[moreButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[moreButton setTitle:@"点击展开更多结果" forState:UIControlStateNormal];
#pragma mark Action - 显示列表
@weakify(self);
[[moreButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(UIButton *x) {
@strongify(self);
[x removeFromSuperview];
[self resetTableView];
}];
moreButton.layer.shadowColor = [UIColor blackColor].CGColor;
moreButton.layer.shadowOpacity = 0.6;
moreButton.layer.shadowOffset = CGSizeMake(0, -2);
[self.view addSubview:moreButton];
moreButton.width = kScreenWidth;
moreButton.height = 50.0;
moreButton.bottom = self.view.frame.size.height;
}
return _moreButton;
}
- (UIView *)searchView{
if (!_searchView) {
UIView *searchView = [[UIView alloc] init];
_searchView = searchView;
searchView.backgroundColor = [UIColor whiteColor];
searchView.layer.shadowColor = [UIColor blackColor].CGColor;
searchView.layer.shadowOpacity = 0.6;
searchView.layer.shadowOffset = CGSizeMake(0, 1);
searchView.layer.cornerRadius = kCornerRadius;
[self.view addSubview:searchView];
// searchView.top = self.topBar.bottom + 10.0;
searchView.top = self.view.top + 10;
searchView.left = 10.0;
searchView.height = 44.0;
searchView.width = kScreenWidth - searchView.left * 2;
@weakify(self);
#pragma mark Action - 移除搜索视图
UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
[closeButton setImage:[UIImage imageNamed:@"live_close_black"] forState:UIControlStateNormal];
[[closeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
@strongify(self);
[self.searchView removeFromSuperview];
}];
[searchView addSubview:closeButton];
[closeButton sizeToFit];
closeButton.right = searchView.width - 10.0;
closeButton.centerY = searchView.height / 2;
UIView *line = [[UIView alloc] init];
line.userInteractionEnabled = NO;
line.backgroundColor = kBorderColor;
[searchView addSubview:line];
line.width = CGFloatFromPixel(1.0);
line.right = closeButton.left - 10.0;
line.top = 8.0;
line.height = searchView.height - line.top * 2;
UITextField *searchTextField = [[UITextField alloc] init];
searchTextField.delegate = self;
searchTextField.borderStyle = UITextBorderStyleNone;
searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
searchTextField.placeholder = @"关键字";
searchTextField.returnKeyType = UIReturnKeySearch;
searchTextField.font = [UIFont systemFontOfSize:16];
searchTextField.textColor = kTextColor;
[searchTextField becomeFirstResponder];
[searchView addSubview:searchTextField];
searchTextField.left = 10.0;
searchTextField.width = line.left - searchTextField.left - 10.0;
searchTextField.height = searchView.height;
}
return _searchView;
}
- (BMKPoiSearch *)poiSearch{
if (!_poiSearch) {
_poiSearch = [[BMKPoiSearch alloc] init];
_poiSearch.delegate = self;
}
return _poiSearch;
}
- (NSMutableArray<POIAnnotation *> *)poiAnnotations{
if (!_poiAnnotations) {
_poiAnnotations = [[NSMutableArray alloc] init];
}
return _poiAnnotations;
}
- (NSArray *)sortedAnnotations{
if (!_sortedAnnotations) {
_sortedAnnotations = [[NSMutableArray alloc] init];
}
return _sortedAnnotations;
}
#pragma mark - TableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.sortedAnnotations.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
LivePoiCell *cell = [tableView dequeueReusableCellWithIdentifier:kLivePoiCellID];
POIAnnotation *annotation = self.sortedAnnotations[indexPath.row];
[cell refreshData:annotation];
cell.delegate = self;
return cell;
}
#pragma mark - TableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
LivePoiSectionHeader *sectionHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kLivePoiSectionHeaderID];
[sectionHeader refreshData:self.sortType];
sectionHeader.delegate = self;
return sectionHeader;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 44.0;
}
#pragma mark - LivePoiCellDelegate
#pragma mark 打电话
- (void)clickPhoneButton:(LivePoiCell *)cell{
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
POIAnnotation *annotation = self.sortedAnnotations[indexPath.row];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", annotation.phone]]];
}
#pragma mark 导航
- (void)clickNavigationButton:(LivePoiCell *)cell{
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
POIAnnotation *annotation = self.sortedAnnotations[indexPath.row];
[self navigate:annotation];
}
#pragma mark - LivePoiSectionHeaderDelegate
#pragma mark 筛选
- (void)clickTypeButton:(LivePoiSectionHeader *)sectionHeader withType:(TVPOIType)type{
self.sortType = type;
NSMutableArray *annotations = [[NSMutableArray alloc] init];
for (POIAnnotation *annotation in self.poiAnnotations) {
if (self.sortType & annotation.type) {
[annotations addObject:annotation];
}
}
self.sortedAnnotations = annotations;
[self.mapView removeAnnotations:self.mapView.annotations];
[self.mapView addAnnotations:self.sortedAnnotations];
// [self.mapView showAnnotations:self.sortedAnnotations edgePadding:UIEdgeInsetsMake(20, 20, self.mapView.height - self.tableView.contentInset.top + 20, 20) animated:NO];
[self.tableView reloadData];
}
#pragma mark - TextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
[self searchPoiByKeywords:textField.text];
return YES;
}
#pragma mark - HandleAction
#pragma mark 滑动列表
- (void)handlePan:(UIPanGestureRecognizer *)pan{
CGPoint offset = [pan translationInView:pan.view];
if (pan.state == UIGestureRecognizerStateBegan) {
_beginOffsetY = offset.y;
}else if (pan.state == UIGestureRecognizerStateChanged) {
if ((offset.y - _beginOffsetY < 0) && self.tableView.contentInset.top > 0) {
pan.enabled = NO;
[_searchView removeFromSuperview];
[UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseIn animations:^{
self.tableView.contentInset = UIEdgeInsetsZero;
} completion:^(BOOL finished) {
pan.enabled = YES;
}];
}else if ((offset.y - _beginOffsetY > 0) && self.tableView.contentOffset.y <= 0) {
pan.enabled = NO;
[UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseIn animations:^{
[self.tableView setContentOffset:CGPointMake(self.tableView.contentOffset.x, -self.tableView.height)];
} completion:^(BOOL finished) {
pan.enabled = YES;
self.tableView.hidden = YES;
self.moreButton.hidden = NO;
}];
// [self.mapView showAnnotations:self.sortedAnnotations edgePadding:UIEdgeInsetsMake(20, 20, 20, 20) animated:YES];
}
}
}
#pragma mark 重置列表
- (void)resetTableView
{
[_moreButton removeFromSuperview];
self.tableView.hidden = NO;
self.tableView.contentInset = UIEdgeInsetsMake(kScreenWidth * 0.5625, 0, 0, 0);
[UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationCurveEaseIn animations:^{
[self.tableView setContentOffset:CGPointMake(0, -self.tableView.contentInset.top)];
} completion:NULL];
/* 如果有多个结果, 设置地图使所有的annotation都可见. */
// [self.mapView showAnnotations:self.sortedAnnotations edgePadding:UIEdgeInsetsMake(20, 20, self.mapView.height - self.tableView.contentInset.top + 20, 20) animated:YES];
}
#pragma mark - Utility
#pragma mark 定位
- (void)locate{
// @weakify(self);
// [[UserLocationManager sharedManager] startLocationWithCompletionHandler:^(UserLocationModel *userLocation, NSError *error) {
// @strongify(self);
// if (error) {
// [TVProgressHUD showErrorWithStatus:error.localizedDescription];
// }else {
// [self.locateButton setTitle:userLocation.Street forState:UIControlStateNormal];
// self.city = userLocation.City;
// self.location = userLocation.coordinate;
// [self searchPoiByCenterCoordinate:userLocation.coordinate];
// }
// }];
_geoCodeSearch = [[BMKGeoCodeSearch alloc] init];
_geoCodeSearch.delegate = self;
// 开始定位
[self startLocation];
[self searchPoiByCenterCoordinate:self.location];
}
//开始定位
-(void)startLocation{
// 初始化BMKLocationService
_locService = [[BMKLocationService alloc]init];
_locService.delegate = self;
_locService.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[_locService startUserLocationService];
}
#pragma mark 根据定位点搜索加油站
- (void)searchPoiByCenterCoordinate:(CLLocationCoordinate2D)coordinate{
_poiSearch = [[BMKPoiSearch alloc] init];
_poiSearch.delegate = self;
//发起检索
BMKPOINearbySearchOption *option = [[BMKPOINearbySearchOption alloc]init];
option.pageIndex = curPage;
option.pageSize = 10;
option.location = self.locationcoord2d;
option.keywords = @[@"中石化",@"中石油"];
// option.tags = @[@"加油站",@"油站"];
option.radius = 5000;
option.isRadiusLimit = false;
option.scope = BMK_POI_SCOPE_DETAIL_INFORMATION;
BMKPOISearchFilter *searchFilter = [[BMKPOISearchFilter alloc] init];
searchFilter.industryType = BMK_POI_INDUSTRY_TYPE_LIFE;
searchFilter.sortBasis = BMK_POI_SORT_BASIS_TYPE_LIFE_DISTANCE;
searchFilter.sortRule = BMK_POI_SORT_RULE_ASCENDING;
// searchFilter.isGroupon
// searchFilter.isDiscount
option.filter = searchFilter;
BOOL flag = [_poiSearch poiSearchNearBy:option];
// option = nil;
if(flag)
{
NSLog(@"周边检索发送成功");
}
else
{
NSLog(@"周边检索发送失败");
}
// request.location = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
// request.types = @"加油站";
// request.keywords = @"中石化|中石油";
// request.radius = 5000;
// /* 按照距离排序. */
// request.sortrule = 0;
// request.requireExtension = YES;
//
// [self.search AMapPOIAroundSearch:request];
}
#pragma mark 根据关键字搜索加油站
- (void)searchPoiByKeywords:(NSString *)keywords{
_poiSearch = [[BMKPoiSearch alloc] init];
_poiSearch.delegate = self;
BMKPOICitySearchOption *citySearchOption = [[BMKPOICitySearchOption alloc]init];
citySearchOption.pageIndex = curPage;
citySearchOption.pageSize = 10;
if (!self.city) {
JKAlertView *alertView = [JKAlertView alertViewWithTitle:@"提示" message:@"您尚未定位,不能使用搜索功能" style:(JKAlertStylePlain)];
[alertView addAction:[JKAlertAction actionWithTitle:@"确定" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
}]];
alertView.enableDeallocLog(YES).show().setDismissComplete(^{
});
return;
}
citySearchOption.tags = @[@"加油站",@"油站"];
citySearchOption.city = self.city;
citySearchOption.keyword = keywords;
citySearchOption.scope = BMK_POI_SCOPE_DETAIL_INFORMATION;
citySearchOption.isCityLimit = YES;
citySearchOption.pageIndex = curPage;
citySearchOption.pageSize = 10;
BMKPOISearchFilter *searchFilter = [[BMKPOISearchFilter alloc] init];
searchFilter.industryType = BMK_POI_INDUSTRY_TYPE_LIFE;
searchFilter.sortBasis = BMK_POI_SORT_BASIS_TYPE_LIFE_DISTANCE;
searchFilter.sortRule = BMK_POI_SORT_RULE_ASCENDING;
citySearchOption.filter = searchFilter;
BOOL flag = [_poiSearch poiSearchInCity:citySearchOption];
if(flag) {
NSLog(@"城市内检索发送成功");
}
else {
NSLog(@"城市内检索发送失败");
}
}
#pragma mark 导航
- (void)navigate:(POIAnnotation *)poi{
if (!self.navigationItem.leftBarButtonItem) {
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_leftBtn];
}
if (self.location.latitude == 0 && self.location.longitude == 0 ) {
[SVProgressHUD showErrorWithStatus:@"定位失败,无法进行导航"];
return;
}
// NSURL *scheme = [NSURL URLWithString:@"iosamap://"];
// BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:scheme];
// if (canOpen) {
// NSString *navigationScheme = [NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&poiname=%@&poiid=%@&lat=%f&lon=%f&dev=1&style=2", [AppInfo appName], poi.title, poi.uid, self.location.latitude, self.location.longitude];
// navigationScheme = [navigationScheme stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
// NSURL *URL = [NSURL URLWithString:navigationScheme];
// if (kiOS10Later) { // iOS10以后,使用新API
// [[UIApplication sharedApplication] openURL:URL options:nil completionHandler:NULL];
// }else { // iOS10以前,使用旧API
// [[UIApplication sharedApplication] openURL:URL];
// }
// }else {
// [TVProgressHUD showErrorWithStatus:@"打开高德地图失败"];
// }
NSArray *arrMap = [self getInstalledMapAppWithEndLocation:poi.coordinate];
if (arrMap.count) {
JKAlertView *alertView = [JKAlertView alertViewWithTitle:@"提示" message:@"车主汇想要打开第三方地图" style:(JKAlertStyleActionSheet)];
for (NSDictionary *dicMap in arrMap) {
__block NSDictionary *bdicMap = dicMap;
[alertView addAction:[JKAlertAction actionWithTitle:dicMap[@"title"] style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
NSString *stitle = bdicMap[@"title"];
TVMapType tvmaptype = (TVMapType)([bdicMap[@"maptype"] intValue]);
NSURL *URL = [NSURL URLWithString:bdicMap[@"url"]];
if (tvmaptype == TVMapTypeiosamap) {
if (kiOS10Later) { // iOS10以后,使用新API
[[UIApplication sharedApplication] openURL:URL options:nil completionHandler:NULL];
}else { // iOS10以前,使用旧API
[[UIApplication sharedApplication] openURL:URL];
}
}else if(tvmaptype == TVMapTypeapple){
CLLocationCoordinate2D locationCoord = ((CLLocation *)(dicMap[@"endLocation"])).coordinate;
[self navAppleMap:locationCoord];
}else{
[[UIApplication sharedApplication] openURL:URL];
}
}]];
bdicMap = nil;
//
}
}else{
JKAlertView *alertView = [JKAlertView alertViewWithTitle:@"提示" message:@"您没有安装<车主汇>可以打开的第三方地图,请安装[百度地图][高德地图][谷歌地图][腾讯地图][苹果地图]其中任意一款地图" style:(JKAlertStylePlain)];
[alertView addAction:[JKAlertAction actionWithTitle:@"确定" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
}]];
alertView.enableDeallocLog(YES).show().setDismissComplete(^{
});
}
}
#pragma mark - 导航方法
- (NSArray *)getInstalledMapAppWithEndLocation:(CLLocationCoordinate2D)endLocation{
NSMutableArray *maps = [NSMutableArray array];
//苹果地图
NSMutableDictionary *iosMapDic = [NSMutableDictionary dictionary];
iosMapDic[@"title"] = @"苹果地图";
iosMapDic[@"maptype"] = @(TVMapTypeapple);
CLLocation *location = [[CLLocation alloc] initWithLatitude:endLocation.latitude longitude:endLocation.longitude];
iosMapDic[@"endLocation"] = location;
// NSMutableArray *muarEndLoc = [[NSMutableArray alloc] init];
// [muarEndLoc addObject:endLocation];
[maps addObject:iosMapDic];
//百度地图
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://map/"]]) {
NSMutableDictionary *baiduMapDic = [NSMutableDictionary dictionary];
baiduMapDic[@"title"] = @"百度地图";
baiduMapDic[@"maptype"] = @(TVMapTypebaidumap);
NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=北京&mode=driving&coord_type=gcj02",endLocation.latitude,endLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
baiduMapDic[@"url"] = urlString;
[maps addObject:baiduMapDic];
}
//高德地图
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
NSMutableDictionary *gaodeMapDic = [NSMutableDictionary dictionary];
gaodeMapDic[@"title"] = @"高德地图";
gaodeMapDic[@"maptype"] = @(TVMapTypeiosamap);
NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=0&style=2",@"导航功能",@"AutoOwnerTV",endLocation.latitude,endLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
gaodeMapDic[@"url"] = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
[maps addObject:gaodeMapDic];
}
//谷歌地图
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"comgooglemaps://"]]) {
NSMutableDictionary *googleMapDic = [NSMutableDictionary dictionary];
googleMapDic[@"title"] = @"谷歌地图";
googleMapDic[@"maptype"] = @(TVMapTypecomgoolemaps);
NSString *urlString = [[NSString stringWithFormat:@"comgooglemaps://?x-source=%@&x-success=%@&saddr=&daddr=%f,%f&directionsmode=driving",@"导航测试",@"nav123456",endLocation.latitude, endLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
googleMapDic[@"url"] = urlString;
[maps addObject:googleMapDic];
}
//腾讯地图
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"qqmap://"]]) {
NSMutableDictionary *qqMapDic = [NSMutableDictionary dictionary];
qqMapDic[@"title"] = @"腾讯地图";
qqMapDic[@"maptype"] = @(TVMapTypeqqmap);
NSString *urlString = [[NSString stringWithFormat:@"qqmap://map/routeplan?from=我的位置&type=drive&tocoord=%f,%f&to=终点&coord_type=1&policy=0",endLocation.latitude, endLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
qqMapDic[@"url"] = urlString;
[maps addObject:qqMapDic];
}
return maps;
}
//苹果地图
- (void)navAppleMap:(CLLocationCoordinate2D)destinationCoordinate2D
{
CLLocationCoordinate2D gps = [JZLocationConverter bd09ToWgs84:destinationCoordinate2D];
MKMapItem *currentLoc = [MKMapItem mapItemForCurrentLocation];
MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:gps addressDictionary:nil]];
NSArray *items = @[currentLoc,toLocation];
NSDictionary *dic = @{
MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving,
MKLaunchOptionsMapTypeKey : @(MKMapTypeStandard),
MKLaunchOptionsShowsTrafficKey : @(YES)
};
[MKMapItem openMapsWithItems:items launchOptions:dic];
}
#pragma mark -
#pragma mark implement BMKMapViewDelegate
/**
*根据anntation生成对应的View
*@param mapView 地图View
*@param annotation 指定的标注
*@return 生成的标注View
*/
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
// 生成重用标示identifier
NSString *AnnotationViewID = @"annotationViewID";
// 检查是否有重用的缓存
BMKAnnotationView* annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
// 缓存没有命中,自己构造一个,一般首次添加annotation代码会运行到此处
if (annotationView == nil) {
annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
// 设置重天上掉下的效果(annotation)
((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
}
// 设置位置
annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
annotationView.annotation = annotation;
// 单击弹出泡泡,弹出泡泡前提annotation必须实现title属性
annotationView.canShowCallout = YES;
// 设置是否可以拖拽
annotationView.draggable = NO;
return annotationView;
}
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
[mapView bringSubviewToFront:view];
[mapView setNeedsDisplay];
}
- (void)mapView:(BMKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
NSLog(@"didAddAnnotationViews");
}
#pragma mark -
#pragma mark implement BMKSearchDelegate
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPOISearchResult*)result errorCode:(BMKSearchErrorCode)error
{
// 清楚屏幕中所有的annotation
NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
[_mapView removeAnnotations:array];
if (error == BMK_SEARCH_NO_ERROR) {
NSMutableArray *annotations = [NSMutableArray array];
for (int i = 0; i < result.poiInfoList.count; i++) {
BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
item.coordinate = poi.pt;
item.title = poi.name;
POIAnnotation *poiA = [[POIAnnotation alloc] initWithPOI:item];
poiA.phone = poi.phone;
poiA.distance = poi.detailInfo.distance;
poiA.address = poi.address;
[annotations addObject:poiA];
}
self.poiAnnotations = annotations;
self.sortedAnnotations = self.poiAnnotations;
[_mapView addAnnotations:annotations];
[_mapView showAnnotations:annotations animated:YES];
[self.tableView reloadData];
[self resetTableView];
} else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR){
NSLog(@"起始点有歧义");
} else {
// 各种情况的判断。。。
}
}
#pragma mark - 定位delegate 处理位置信息更新
// 处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation{
[_mapView updateLocationData:userLocation];
}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
//普通态
//以下_mapView为BMKMapView对象
dispatch_async(dispatch_get_main_queue(), ^{
[_mapView updateLocationData:userLocation]; //更新地图上的位置
});
self.locationcoord2d = userLocation.location.coordinate;
_mapView.centerCoordinate = userLocation.location.coordinate; //更新当前位置到地图中间
//发起中心点检索
if (userLocation.location) {
[self searchPoiByCenterCoordinate:userLocation.location.coordinate];
}
//地理反编码
BMKReverseGeoCodeSearchOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeSearchOption alloc]init];
reverseGeocodeSearchOption.location = userLocation.location.coordinate;
BOOL flag = [_geoCodeSearch reverseGeoCode:reverseGeocodeSearchOption];
if(flag){
NSLog(@"反geo检索发送成功");
[_locService stopUserLocationService];
}else{
NSLog(@"反geo检索发送失败");
}
}
- (void)didStopLocatingUser{
NSLog(@"stop locate");
}
#pragma mark -------------地理反编码的delegate---------------
/**
*返回反地理编码搜索结果
*@param searcher 搜索对象
*@param result 搜索结果
*@param error 错误号,@see BMKSearchErrorCode
*/
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeSearchResult *)result errorCode:(BMKSearchErrorCode)error{
NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
[_mapView removeAnnotations:array];
array = [NSArray arrayWithArray:_mapView.overlays];
[_mapView removeOverlays:array];
//addressDetail: 层次化地址信息
if (error == BMK_SEARCH_NO_ERROR) {
self.city = result.addressDetail.city;
[self.leftBtn setTitle:self.city forState:UIControlStateNormal];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.leftBtn];
if ([self.delegate respondsToSelector:@selector(setlocationBtn:)]) {
[self.delegate setlocationBtn:self.navigationItem.leftBarButtonItem];
}
self.province = result.addressDetail.province;
//address: 地址名称
self.address = result.address;
NSArray <BMKPoiInfo *> *arr = result.poiList;
}else{
//没有找到检索结果
}
//businessCircle: 商圈名称
// location: 地址坐标
// poiList: 地址周边POI信息,成员类型为BMKPoiInfo
}
//定位失败
- (void)didFailToLocateUserWithError:(NSError *)error{
NSLog(@"error:%@",error);
}
/**
*返回地址信息搜索结果
*@param searcher 搜索对象
*@param result 搜索结BMKGeoCodeSearch果
*@param error 错误号,@see BMKSearchErrorCode
*/
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeSearchResult *)result errorCode:(BMKSearchErrorCode)error{
}
//#pragma mark - MAMapViewDelegate
//
//- (void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
//{
// id<MAAnnotation> annotation = view.annotation;
//
// if ([annotation isKindOfClass:[POIAnnotation class]])
// {
// POIAnnotation *poiAnnotation = (POIAnnotation*)annotation;
// [self navigate:poiAnnotation.poi];
// }
//}
//
//- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
//{
// if ([annotation isKindOfClass:[POIAnnotation class]])
// {
// static NSString *poiIdentifier = @"poiIdentifier";
// MAAnnotationView *poiAnnotationView = [self.mapView dequeueReusableAnnotationViewWithIdentifier:poiIdentifier];
// if (poiAnnotationView == nil)
// {
// poiAnnotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:poiIdentifier];
// }
//
// POIAnnotation *poiAnnotation = (POIAnnotation *)annotation;
// switch (poiAnnotation.type) {
// case TVPOIOil:
// poiAnnotationView.image = [UIImage imageNamed:@"live_oil"];
// break;
// case TVPOIGas:
// poiAnnotationView.image = [UIImage imageNamed:@"live_gas"];
// break;
// default:
// poiAnnotationView.image = [[UIImage imageNamed:@"live_oilBag"] imageByResizeToSize:CGSizeMake(30, 30)];
// break;
// }
// poiAnnotationView.canShowCallout = YES;
// UIButton *detailButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
// detailButton.tintColor = kThemeColor;
// poiAnnotationView.rightCalloutAccessoryView = detailButton;
//
// return poiAnnotationView;
// }
//
// return nil;
//}
//
//#pragma mark - AMapSearchDelegate
//
//- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
//{
// DDLogError(@"%@", error);
//}
//
///* POI 搜索回调. */
//- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
//{
// [self.mapView removeAnnotations:self.mapView.annotations];
// [self.poiAnnotations removeAllObjects];
// self.sortType |= TVPOIOil;
// self.sortType |= TVPOIGas;
// self.sortType |= TVPOIOther;
//
// if (response.pois.count == 0)
// {
// [TVProgressHUD showInfoWithStatus:@"查无结果"];
// return;
// }
//
// [response.pois enumerateObjectsUsingBlock:^(AMapPOI *obj, NSUInteger idx, BOOL *stop) {
//
// [self.poiAnnotations addObject:[[POIAnnotation alloc] initWithPOI:obj]];
//
// }];
// self.sortedAnnotations = self.poiAnnotations;
// /* 将结果以annotation的形式加载到地图上. */
// [self.mapView addAnnotations:self.sortedAnnotations];
//
// [self.tableView reloadData];
// [self resetTableView];
//}
@end
mode类
POIAnnotation
#import <Foundation/Foundation.h>
#import <BaiduMapAPI_Map/BMKPointAnnotation.h>
/**
poi类型
*/
typedef NS_ENUM(NSInteger, TVPOIType) {
TVPOIOil = 1 << 0,
TVPOIGas = 1 << 1,
TVPOIOther = 1 << 2
};
/**
poi标注点
*/
@interface POIAnnotation : BMKPointAnnotation
/**
构造方法
@param poi poi
@return 实例
*/
- (id)initWithPOI:(BMKPointAnnotation *)poi;
/**
poi
*/
@property (nonatomic, strong) BMKPointAnnotation *poi;
/**
经纬度
*/
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
/**
poi类型
*/
@property (nonatomic, assign) TVPOIType type;
@property (nonatomic, copy) NSString *phone;
@property (nonatomic, assign) NSInteger distance;
@property (nonatomic, copy) NSString *address;
/*!
@brief 获取annotation标题
@return 返回annotation的标题信息
*/
- (NSString *)title;
/*!
@brief 获取annotation副标题
@return 返回annotation的副标题信息
*/
- (NSString *)subtitle;
/***
电话
*/
@end
#import "POIAnnotation.h"
#import <BaiduMapAPI_Map/BMKPointAnnotation.h>
/**
poi类型
*/
//typedef NS_ENUM(NSInteger, TVPOIType) {
// TVPOIOil = 1 << 0,
// TVPOIGas = 1 << 1,
// TVPOIOther = 1 << 2
//};
/**
poi标注点
*/
@implementation POIAnnotation
- (NSString *)title
{
return self.poi.title;
}
- (NSString *)subtitle
{
return self.poi.subtitle;
}
- (CLLocationCoordinate2D)coordinate
{
return self.poi.coordinate;
}
#pragma mark - Life Cycle
- (id)initWithPOI:(BMKPointAnnotation *)poi
{
if (self = [super init])
{
self.poi = poi;
if ([poi.title containsString:@"中石化"]) {
self.type = TVPOIOil;
}else if ([poi.title containsString:@"中石油"]) {
self.type = TVPOIGas;
}else {
self.type = TVPOIOther;
}
}
return self;
}
@end
LivePoiTableView
//
// LivePoiTableView.m
//
// Created by BoxingWoo on 2017/10/12.
// Copyright © 2017年 autotv. All rights reserved.
//
#import "LivePoiTableView.h"
@implementation LivePoiTableView
- (void)reloadData
{
[super reloadData];
CGFloat height = self.height + self.tableFooterView.height - self.contentSize.height;
if (height > 0) {
UIView *tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, height)];
tableFooterView.backgroundColor = [UIColor whiteColor];
self.tableFooterView = tableFooterView;
}else {
self.tableFooterView = nil;
}
}
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
UIView *view = [super hitTest:point withEvent:event];
if ([view isKindOfClass:[UITableView class]]) {
return nil;
}else {
return view;
}
}
@end
LivePoiSectionHeader
//
// LivePoiSectionHeader.h
#import <UIKit/UIKit.h>
#import "POIAnnotation.h"
@class LivePoiSectionHeader;
/**
poi节头
*/
@protocol LivePoiSectionHeaderDelegate <NSObject>
/**
点击筛选类型按钮代理方法
*/
- (void)clickTypeButton:(LivePoiSectionHeader *)sectionHeader withType:(TVPOIType)type;
@end
@interface LivePoiSectionHeader : UITableViewHeaderFooterView
/**
按钮数组
*/
@property (nonatomic, copy) NSArray <UIButton *> *buttons;
/**
代理
*/
@property (nonatomic, assign) id<LivePoiSectionHeaderDelegate> delegate;
/**
刷新数据
@param type 筛选类型
*/
- (void)refreshData:(TVPOIType)type;
@end
//
// LivePoiSectionHeader.m
#import "LivePoiSectionHeader.h"
@interface LivePoiSectionHeader ()
@property (nonatomic, assign) TVPOIType type;
@property (nonatomic, weak) UIView *line;
@end
@implementation LivePoiSectionHeader
- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [super initWithReuseIdentifier:reuseIdentifier]) {
self.contentView.backgroundColor = [UIColor whiteColor];
NSArray *arr = @[@{@"title":@"中石化", @"type":@(TVPOIOil)}, @{@"title":@"中石油", @"type":@(TVPOIGas)}];
NSMutableArray *buttons = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < arr.count; i++) {
NSDictionary *dict = arr[i];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.titleLabel.font = [UIFont systemFontOfSize:12];
[button setTitleColor:kTextColor forState:UIControlStateSelected];
// [button setBackgroundImage:[UIImage imageWithColor:kThemeColor size:button.frame.size] forState:UIControlStateSelected];
[button setTitleColor:kGrayTextColor forState:UIControlStateNormal];
// [button setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor] size:button.frame.size] forState:UIControlStateNormal];
[button setTitle:dict[@"title"] forState:UIControlStateNormal];
button.layer.borderColor = kGrayTextColor.CGColor;
button.layer.borderWidth = CGFloatFromPixel(1);
button.layer.cornerRadius = 15;
[button setBackgroundImage:[[UIImage imageWithColor:kBorderColor size:CGSizeMake(60, 30)] imageByRoundCornerRadius:15] forState:UIControlStateNormal];
[button setBackgroundImage:[[UIImage imageWithColor:kThemeColor size:CGSizeMake(60, 30)] imageByRoundCornerRadius:15] forState:UIControlStateSelected];
[button addTarget:self action:@selector(handleSort:) forControlEvents:UIControlEventTouchUpInside];
button.tag = [dict[@"type"] integerValue];
[buttons addObject:button];
[self.contentView addSubview:button];
UIView *line = [[UIView alloc] init];
_line = line;
line.userInteractionEnabled = NO;
line.backgroundColor = [UIColor colorWithWhite:221 / 255.0 alpha:1.0];
[self.contentView addSubview:line];
}
_buttons = buttons;
}
return self;
}
- (void)handleSort:(UIButton *)button
{
button.selected = !button.isSelected;
if (button.isSelected) {
self.type |= button.tag;
button.layer.borderColor = kThemeColor.CGColor;
}else {
self.type ^= button.tag;
button.layer.borderColor = kGrayTextColor.CGColor;
}
[self.delegate clickTypeButton:self withType:self.type];
}
- (void)refreshData:(TVPOIType)type
{
self.type = type;
for (UIButton *button in self.buttons) {
button.selected = self.type & button.tag;
}
}
- (void)layoutSubviews
{
[super layoutSubviews];
for (NSInteger i = 0; i < self.buttons.count; i++) {
UIButton *button = self.buttons[i];
button.frame = CGRectMake(20 + (60 + 10) * i, (self.contentView.height - 30) / 2, 60, 30);
}
self.line.width = self.contentView.width;
self.line.height = CGFloatFromPixel(1.0);
self.line.bottom = self.contentView.height - self.line.height;
}
@end

浙公网安备 33010602011771号