### Search Walking Route in Objective-C Source: https://context7.com/baidulbs/baidumapkit/llms.txt Calculates walking routes between a start and end point. The result provides the total distance and estimated duration for the walk. ```Objective-C // 步行路线规划 - (void)searchWalkingRoute { BMKWalkingRoutePlanOption *option = [[BMKWalkingRoutePlanOption alloc] init]; BMKPlanNode *from = [[BMKPlanNode alloc] init]; from.pt = CLLocationCoordinate2DMake(39.915, 116.404); option.from = from; BMKPlanNode *to = [[BMKPlanNode alloc] init]; to.pt = CLLocationCoordinate2DMake(39.920, 116.410); option.to = to; [self.routeSearch walkingSearch:option]; } ``` -------------------------------- ### Search Riding Route in Objective-C Source: https://context7.com/baidulbs/baidumapkit/llms.txt Plans cycling routes between specified start and end coordinates. The output includes the distance and estimated time for the cycling journey. ```Objective-C // 骑行路线规划 - (void)searchRidingRoute { BMKRidingRoutePlanOption *option = [[BMKRidingRoutePlanOption alloc] init]; BMKPlanNode *from = [[BMKPlanNode alloc] init]; from.pt = CLLocationCoordinate2DMake(39.915, 116.404); option.from = from; BMKPlanNode *to = [[BMKPlanNode alloc] init]; to.pt = CLLocationCoordinate2DMake(39.930, 116.420); option.to = to; [self.routeSearch ridingSearch:option]; } ``` -------------------------------- ### Manage Offline Maps with BMKOfflineMap Source: https://context7.com/baidulbs/baidumapkit/llms.txt Demonstrates how to initialize the offline map manager, search for cities, and perform download, update, and deletion operations. It also includes delegate methods to track download status and updates. ```objectivec #import #import @interface OfflineMapViewController () @property (nonatomic, strong) BMKOfflineMap *offlineMap; @end @implementation OfflineMapViewController - (void)viewDidLoad { [super viewDidLoad]; self.offlineMap = [[BMKOfflineMap alloc] init]; self.offlineMap.delegate = self; } - (void)getHotCities { NSArray *hotCities = [self.offlineMap getHotCityList]; for (BMKOLSearchRecord *city in hotCities) { NSLog(@"热门城市: %@ (ID: %d, 大小: %d bytes)", city.cityName, city.cityID, city.size); } } - (void)getAllOfflineCities { NSArray *allCities = [self.offlineMap getOfflineCityList]; NSLog(@"共 %lu 个城市支持离线地图", (unsigned long)allCities.count); } - (void)searchCity:(NSString *)cityName { NSArray *results = [self.offlineMap searchCity:cityName]; for (BMKOLSearchRecord *city in results) { NSLog(@"找到城市: %@ (ID: %d)", city.cityName, city.cityID); for (BMKOLSearchRecord *child in city.childCities) { NSLog(@" - %@ (ID: %d)", child.cityName, child.cityID); } } } - (void)downloadOfflineMap:(int)cityID { BOOL result = [self.offlineMap start:cityID]; if (result) { NSLog(@"开始下载城市 ID: %d", cityID); } else { NSLog(@"下载启动失败"); } } - (void)pauseDownload:(int)cityID { [self.offlineMap pause:cityID]; NSLog(@"暂停下载城市 ID: %d", cityID); } - (void)updateOfflineMap:(int)cityID { [self.offlineMap update:cityID]; NSLog(@"更新城市 ID: %d", cityID); } - (void)deleteOfflineMap:(int)cityID { [self.offlineMap remove:cityID]; NSLog(@"删除城市 ID: %d", cityID); } - (void)getDownloadStatus { NSArray *updateInfos = [self.offlineMap getAllUpdateInfo]; for (BMKOLUpdateElement *info in updateInfos) { NSLog(@"城市: %@ (ID: %d)", info.cityName, info.cityID); NSLog(@" 状态: %d", info.status); NSLog(@" 已下载: %d / %d bytes", info.size, info.serverSize); NSLog(@" 进度: %.1f%%", info.ratio * 100); } } - (void)getCityStatus:(int)cityID { BMKOLUpdateElement *info = [self.offlineMap getUpdateInfo:cityID]; if (info) { NSLog(@"城市 %@ 下载进度: %.1f%%", info.cityName, info.ratio * 100); } } - (void)onGetOfflineMapState:(int)type withState:(int)state { switch (type) { case TYPE_OFFLINE_UPDATE: NSLog(@"正在下载/更新城市 ID: %d", state); break; case TYPE_OFFLINE_NEWVER: NSLog(@"城市 ID: %d 有新版本", state); break; case TYPE_OFFLINE_UNZIPFINISH: NSLog(@"解压完成,成功导入 %d 个离线包", state); break; default: break; } } - (void)dealloc { self.offlineMap.delegate = nil; } @end ``` -------------------------------- ### Baidu Maps POI Search Implementation (Objective-C) Source: https://context7.com/baidulbs/baidumapkit/llms.txt This snippet demonstrates how to implement different POI search functionalities using the BaiduMapAPI_Search SDK in Objective-C. It covers initializing the search object, setting up search options for city, nearby, bounds, detail, and indoor searches, and handling search results and errors via the BMKPoiSearchDelegate protocol. Dependencies include BaiduMapAPI_Search framework. ```Objective-C #import #import #import @interface SearchViewController () @property (nonatomic, strong) BMKPoiSearch *poiSearch; @end @implementation SearchViewController - (void)viewDidLoad { [super viewDidLoad]; self.poiSearch = [[BMKPoiSearch alloc] init]; self.poiSearch.delegate = self; } // 城市内 POI 检索 - (void)searchPOIInCity { BMKPOICitySearchOption *option = [[BMKPOICitySearchOption alloc] init]; option.city = @"北京"; // 城市名称或编码 option.keyword = @"美食"; // 检索关键字 option.tags = @[@"餐厅", @"小吃"]; // 分类标签 option.scope = BMK_POI_SCOPE_DETAIL_INFORMATION; // 返回详细信息 option.pageIndex = 0; // 分页索引 option.pageSize = 20; // 每页数量(最大20) option.isCityLimit = YES; // 限定在城市内 BOOL result = [self.poiSearch poiSearchInCity:option]; if (!result) { NSLog(@"POI 检索发起失败"); } } // 周边 POI 检索 - (void)searchPOINearby { BMKPOINearbySearchOption *option = [[BMKPOINearbySearchOption alloc] init]; option.location = CLLocationCoordinate2DMake(39.915, 116.404); // 中心点 option.keywords = @[@"银行", @"ATM"]; // 关键字数组(最多10个) option.radius = 2000; // 检索半径(米) option.isRadiusLimit = YES; // 严格限制在半径内 option.pageIndex = 0; option.pageSize = 20; [self.poiSearch poiSearchNearBy:option]; } // 矩形区域 POI 检索 - (void)searchPOIInBounds { BMKPOIBoundSearchOption *option = [[BMKPOIBoundSearchOption alloc] init]; option.leftBottom = CLLocationCoordinate2DMake(39.900, 116.390); // 左下角 option.rightTop = CLLocationCoordinate2DMake(39.930, 116.420); // 右上角 option.keywords = @[@"酒店"]; option.pageIndex = 0; option.pageSize = 20; [self.poiSearch poiSearchInbounds:option]; } // POI 详情检索 - (void)searchPOIDetail:(NSString *)poiUID { BMKPOIDetailSearchOption *option = [[BMKPOIDetailSearchOption alloc] init]; option.poiUIDs = @[poiUID]; // POI 唯一标识符 option.scope = BMK_POI_SCOPE_DETAIL_INFORMATION; [self.poiSearch poiDetailSearch:option]; } // 室内 POI 检索 - (void)searchPOIIndoor:(NSString *)indoorID { BMKPOIIndoorSearchOption *option = [[BMKPOIIndoorSearchOption alloc] init]; option.indoorID = indoorID; // 室内图 ID option.keyword = @"咖啡"; option.floor = @"F1"; // 楼层(可选) option.pageIndex = 0; option.pageSize = 10; [self.poiSearch poiIndoorSearch:option]; } #pragma mark - BMKPoiSearchDelegate - (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPOISearchResult *)poiResult errorCode:(BMKSearchErrorCode)errorCode { if (errorCode == BMK_SEARCH_NO_ERROR) { NSLog(@"检索成功,共 %lu 条结果", (unsigned long)poiResult.poiInfoList.count); for (BMKPoiInfo *poi in poiResult.poiInfoList) { NSLog(@"名称: %@", poi.name); NSLog(@"地址: %@", poi.address); NSLog(@"坐标: %.6f, %.6f", poi.pt.latitude, poi.pt.longitude); NSLog(@"UID: %@", poi.uid); NSLog(@"电话: %@", poi.phone); NSLog(@"---"); } // 翻页信息 NSLog(@"总结果数: %d, 总页数: %d", poiResult.totalPOINum, poiResult.totalPageNum); } else if (errorCode == BMK_SEARCH_RESULT_NOT_FOUND) { NSLog(@"未找到结果"); } else { NSLog(@"检索失败,错误码: %d", errorCode); } } - (void)onGetPoiDetailResult:(BMKPoiSearch *)searcher result:(BMKPOIDetailSearchResult *)poiDetailResult errorCode:(BMKSearchErrorCode)errorCode { if (errorCode == BMK_SEARCH_NO_ERROR) { for (BMKPoiDetailInfo *detail in poiDetailResult.poiDetailInfoList) { NSLog(@"详情 - 名称: %@, 评分: %@", detail.name, detail.overallRating); } } } - (void)dealloc { self.poiSearch.delegate = nil; } @end ``` -------------------------------- ### Objective-C: Display and Manage Indoor Maps with BMKMapView Source: https://context7.com/baidulbs/baidumapkit/llms.txt This Objective-C code demonstrates how to enable indoor map display, show indoor POI annotations, switch between floors of an indoor map, and retrieve information about the currently focused indoor map. It also includes delegate methods for handling entry and exit from indoor maps. ```Objective-C #import #import @implementation IndoorMapViewController - (void)setupIndoorMap { // 开启室内地图 self.mapView.baseIndoorMapEnabled = YES; // 显示室内图 POI 标注 self.mapView.showIndoorMapPoi = YES; } // 切换室内图楼层 - (void)switchFloor:(NSString *)floor indoorID:(NSString *)indoorID { BMKSwitchIndoorFloorError error = [self.mapView switchBaseIndoorMapFloor:floor withID:indoorID]; switch (error) { case BMKSwitchIndoorFloorSuccess: NSLog(@"切换楼层成功"); break; case BMKSwitchIndoorFloorFailed: NSLog(@"切换楼层失败"); break; case BMKSwitchIndoorFloorNotFocused: NSLog(@"地图未聚焦到该室内图"); break; case BMKSwitchIndoorFloorNotExist: NSLog(@"该楼层不存在"); break; } } // 获取当前聚焦的室内图信息 - (void)getCurrentIndoorInfo { BMKBaseIndoorMapInfo *info = [self.mapView getFocusedBaseIndoorMapInfo]; if (info) { NSLog(@"室内图 ID: %@", info.strID); NSLog(@"当前楼层: %@", info.strFloor); NSLog(@"所有楼层: %@", info.arrStrFloors); } else { NSLog(@"当前未聚焦任何室内图"); } } #pragma mark - BMKMapViewDelegate // 进入/离开室内图回调 - (void)mapview:(BMKMapView *)mapView baseIndoorMapWithIn:(BOOL)flag baseIndoorMapInfo:(BMKBaseIndoorMapInfo *)info { if (flag) { NSLog(@"进入室内图: %@, 楼层: %@", info.strID, info.strFloor); } else { NSLog(@"离开室内图"); } } @end ``` -------------------------------- ### Implement Geocoding and Reverse Geocoding with BMKGeoCodeSearch Source: https://context7.com/baidulbs/baidumapkit/llms.txt This snippet demonstrates how to initialize the BMKGeoCodeSearch service, perform geocoding and reverse geocoding requests, and handle the asynchronous results via the BMKGeoCodeSearchDelegate protocol. ```objectivec #import #import #import @interface GeoCodeViewController () @property (nonatomic, strong) BMKGeoCodeSearch *geoSearch; @end @implementation GeoCodeViewController - (void)viewDidLoad { [super viewDidLoad]; self.geoSearch = [[BMKGeoCodeSearch alloc] init]; self.geoSearch.delegate = self; } - (void)geocodeAddress { BMKGeoCodeSearchOption *option = [[BMKGeoCodeSearchOption alloc] init]; option.city = @"北京市"; option.address = @"海淀区上地十街10号"; BOOL result = [self.geoSearch geoCode:option]; if (!result) { NSLog(@"地理编码请求发送失败"); } } - (void)reverseGeocodeLocation { BMKReverseGeoCodeSearchOption *option = [[BMKReverseGeoCodeSearchOption alloc] init]; option.location = CLLocationCoordinate2DMake(39.915, 116.404); option.isLatestAdmin = YES; BOOL result = [self.geoSearch reverseGeoCode:option]; if (!result) { NSLog(@"逆地理编码请求发送失败"); } } - (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeSearchResult *)result errorCode:(BMKSearchErrorCode)error { if (error == BMK_SEARCH_NO_ERROR && result) { NSLog(@"地理编码成功"); } else { NSLog(@"地理编码失败,错误码: %d", error); } } - (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeSearchResult *)result errorCode:(BMKSearchErrorCode)error { if (error == BMK_SEARCH_NO_ERROR && result) { NSLog(@"逆地理编码成功"); } else { NSLog(@"逆地理编码失败,错误码: %d", error); } } - (void)dealloc { self.geoSearch.delegate = nil; } @end ``` -------------------------------- ### Manage Map Annotations with BMKPointAnnotation Source: https://context7.com/baidulbs/baidumapkit/llms.txt Demonstrates creating individual and batch annotations, adding them to the map, and handling their lifecycle through the BMKMapViewDelegate. It includes configuring visual properties like pin color, animation, and interactivity. ```objectivec #import #import #import @implementation MapViewController - (void)addAnnotations { BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc] init]; annotation.coordinate = CLLocationCoordinate2DMake(39.915, 116.404); annotation.title = @"天安门"; annotation.subtitle = @"北京市中心"; [self.mapView addAnnotation:annotation]; NSMutableArray *annotations = [NSMutableArray array]; CLLocationCoordinate2D coords[] = { {39.915, 116.404}, {39.905, 116.414}, {39.925, 116.394} }; for (int i = 0; i < 3; i++) { BMKPointAnnotation *anno = [[BMKPointAnnotation alloc] init]; anno.coordinate = coords[i]; anno.title = [NSString stringWithFormat:@"标注点 %d", i + 1]; [annotations addObject:anno]; } [self.mapView addAnnotations:annotations]; [self.mapView showAnnotations:annotations animated:YES]; } - (void)removeAllAnnotations { [self.mapView removeAnnotations:self.mapView.annotations]; } - (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id)annotation { if ([annotation isKindOfClass:[BMKPointAnnotation class]]) { static NSString *reuseID = @"annotationReuseID"; BMKPinAnnotationView *pinView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseID]; if (!pinView) { pinView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseID]; } pinView.pinColor = BMKPinAnnotationColorRed; pinView.animatesDrop = YES; pinView.draggable = YES; pinView.canShowCallout = YES; return pinView; } return nil; } - (void)mapView:(BMKMapView *)mapView clickAnnotationView:(BMKAnnotationView *)view { NSLog(@"点击标注: %@", view.annotation.title); } - (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view { NSLog(@"选中标注: %@", view.annotation.title); } - (void)mapView:(BMKMapView *)mapView annotationView:(BMKAnnotationView *)view didChangeDragState:(BMKAnnotationViewDragState)newState fromOldState:(BMKAnnotationViewDragState)oldState { if (newState == BMKAnnotationViewDragStateEnding) { CLLocationCoordinate2D newCoord = view.annotation.coordinate; NSLog(@"标注拖拽结束,新位置: %.6f, %.6f", newCoord.latitude, newCoord.longitude); } } @end ``` -------------------------------- ### Add and Render Map Overlays in iOS Source: https://context7.com/baidulbs/baidumapkit/llms.txt This snippet shows how to instantiate geometric overlay objects and implement the BMKMapViewDelegate to define their visual properties like stroke color, fill color, and line width. ```objectivec #import #import #import #import #import #import @implementation MapViewController - (void)addPolyline { CLLocationCoordinate2D coords[4] = {{39.915, 116.404}, {39.905, 116.414}, {39.895, 116.404}, {39.905, 116.394}}; BMKPolyline *polyline = [BMKPolyline polylineWithCoordinates:coords count:4]; [self.mapView addOverlay:polyline]; } - (void)addPolygon { CLLocationCoordinate2D coords[4] = {{39.920, 116.400}, {39.920, 116.410}, {39.910, 116.410}, {39.910, 116.400}}; BMKPolygon *polygon = [BMKPolygon polygonWithCoordinates:coords count:4]; [self.mapView addOverlay:polygon]; } - (void)addCircle { CLLocationCoordinate2D center = CLLocationCoordinate2DMake(39.915, 116.404); BMKCircle *circle = [BMKCircle circleWithCenterCoordinate:center radius:500]; [self.mapView addOverlay:circle]; } - (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id)overlay { if ([overlay isKindOfClass:[BMKPolyline class]]) { BMKPolylineView *polylineView = [[BMKPolylineView alloc] initWithPolyline:(BMKPolyline *)overlay]; polylineView.strokeColor = [UIColor colorWithRed:0 green:0.5 blue:1 alpha:0.8]; polylineView.lineWidth = 5.0; return polylineView; } if ([overlay isKindOfClass:[BMKPolygon class]]) { BMKPolygonView *polygonView = [[BMKPolygonView alloc] initWithPolygon:(BMKPolygon *)overlay]; polygonView.strokeColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.8]; polygonView.fillColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.3]; return polygonView; } if ([overlay isKindOfClass:[BMKCircle class]]) { BMKCircleView *circleView = [[BMKCircleView alloc] initWithCircle:(BMKCircle *)overlay]; circleView.strokeColor = [UIColor colorWithRed:0 green:0.8 blue:0 alpha:0.8]; circleView.fillColor = [UIColor colorWithRed:0 green:0.8 blue:0 alpha:0.2]; return circleView; } return nil; } @end ``` -------------------------------- ### Initialize BaiduMapKit SDK Engine and Manager Source: https://context7.com/baidulbs/baidumapkit/llms.txt Initializes the BaiduMapKit SDK engine using BMKMapManager, which is crucial for API key authentication and enabling map functionalities. It includes setting the coordinate type, enabling logs for debugging, and handling the permission check callback. ```Objective-C #import #import @interface AppDelegate () @property (nonatomic, strong) BMKMapManager *mapManager; @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 创建引擎管理器 self.mapManager = [BMKMapManager sharedInstance]; // 设置全局坐标类型(可选,默认 BD09LL) // BMK_COORDTYPE_BD09LL: 百度经纬度坐标 // BMK_COORDTYPE_COMMON: GCJ02 坐标(高德、腾讯地图坐标系) [BMKMapManager setCoordinateTypeUsedInBaiduMapSDK:BMK_COORDTYPE_BD09LL]; // 开启日志(调试时使用,发布时关闭) [BMKMapManager logEnable:YES module:BMKMapModuleTile]; // 启动引擎,传入 API Key BOOL result = [self.mapManager start:@"您的百度地图API Key" generalDelegate:self]; if (!result) { NSLog(@"引擎启动失败"); } return YES; } #pragma mark - BMKGeneralDelegate 鉴权回调 - (void)onGetPermissionState:(int)iError { if (iError == E_PERMISSIONCHECK_OK) { NSLog(@"鉴权成功"); } else { NSLog(@"鉴权失败,错误码: %d", iError); // 常见错误码: // 101: AK 不存在 // 102: mcode 签名值不正确 // 200: APP 不存在 // 201: APP 被禁用 } } - (void)applicationWillTerminate:(UIApplication *)application { // 停止引擎 [self.mapManager stop]; } @end ``` -------------------------------- ### Initialize Route Search in Objective-C Source: https://context7.com/baidulbs/baidumapkit/llms.txt Initializes the BMKRouteSearch object and sets the delegate for handling route search results. This is a prerequisite for all route planning operations. ```Objective-C #import #import #import @interface RouteViewController () @property (nonatomic, strong) BMKRouteSearch *routeSearch; @end @implementation RouteViewController - (void)viewDidLoad { [super viewDidLoad]; self.routeSearch = [[BMKRouteSearch alloc] init]; self.routeSearch.delegate = self; } ``` -------------------------------- ### Coordinate Conversion with BMKGeometry Source: https://context7.com/baidulbs/baidumapkit/llms.txt Demonstrates how to convert coordinates between different systems (GPS, GCJ02, BD09LL) and convert between geographic coordinates and map points using BMKGeometry. It also shows conversion to Baidu Mercator projection. ```Objective-C #import #import @implementation GeometryUtils // 坐标系转换 - (void)coordinateConversion { // GPS 坐标转百度坐标 CLLocationCoordinate2D gpsCoord = CLLocationCoordinate2DMake(39.908, 116.397); CLLocationCoordinate2D bd09Coord = BMKCoordTrans(gpsCoord, BMK_COORDTYPE_GPS, BMK_COORDTYPE_BD09LL); NSLog(@"GPS -> BD09LL: %.6f, %.6f", bd09Coord.latitude, bd09Coord.longitude); // GCJ02(高德、腾讯)坐标转百度坐标 CLLocationCoordinate2D gcjCoord = CLLocationCoordinate2DMake(39.910, 116.400); CLLocationCoordinate2D bdCoord = BMKCoordTrans(gcjCoord, BMK_COORDTYPE_COMMON, BMK_COORDTYPE_BD09LL); NSLog(@"GCJ02 -> BD09LL: %.6f, %.6f", bdCoord.latitude, bdCoord.longitude); // 百度坐标转 GCJ02 CLLocationCoordinate2D toGcj = BMKCoordTrans(bd09Coord, BMK_COORDTYPE_BD09LL, BMK_COORDTYPE_COMMON); NSLog(@"BD09LL -> GCJ02: %.6f, %.6f", toGcj.latitude, toGcj.longitude); // 经纬度转直角投影坐标 BMKMapPoint mapPoint = BMKMapPointForCoordinate(bd09Coord); NSLog(@"MapPoint: x=%.2f, y=%.2f", mapPoint.x, mapPoint.y); // 直角投影坐标转经纬度 CLLocationCoordinate2D coord = BMKCoordinateForMapPoint(mapPoint); NSLog(@"Coordinate: %.6f, %.6f", coord.latitude, coord.longitude); // 百度经纬度转百度墨卡托坐标 CGPoint mercator = BMKConvertToBaiduMercatorFromBD09LL(bd09Coord); NSLog(@"Mercator: x=%.2f, y=%.2f", mercator.x, mercator.y); } @end ``` -------------------------------- ### Configure Map Location Layer Source: https://context7.com/baidulbs/baidumapkit/llms.txt Shows how to enable the user location layer on a BMKMapView, set tracking modes, and customize the appearance of the location marker and accuracy circle. ```objectivec #import #import #import @implementation LocationViewController - (void)setupLocationLayer { self.mapView.showsUserLocation = YES; self.mapView.userTrackingMode = BMKUserTrackingModeFollow; BMKLocationViewDisplayParam *displayParam = [[BMKLocationViewDisplayParam alloc] init]; displayParam.isAccuracyCircleShow = YES; displayParam.accuracyCircleFillColor = [UIColor colorWithRed:0 green:0.5 blue:1 alpha:0.2]; displayParam.accuracyCircleStrokeColor = [UIColor colorWithRed:0 green:0.5 blue:1 alpha:0.5]; displayParam.locationViewOffsetX = 0; displayParam.locationViewOffsetY = 0; displayParam.locationViewImage = [UIImage imageNamed:@"custom_location_icon"]; [self.mapView updateLocationViewWithParam:displayParam]; } - (void)updateUserLocation:(CLLocation *)location heading:(CLHeading *)heading { BMKUserLocation *userLocation = [[BMKUserLocation alloc] init]; userLocation.location = location; userLocation.heading = heading; [self.mapView updateLocationData:userLocation]; } - (void)checkLocationVisible { if (self.mapView.isUserLocationVisible) { NSLog(@"定位点在可视区域内"); } else { NSLog(@"定位点不在可视区域内"); } } @end ``` -------------------------------- ### Area Calculation with BMKGeometry Source: https://context7.com/baidulbs/baidumapkit/llms.txt Demonstrates how to calculate the area of a rectangular region and a polygon using their respective coordinates. The results are returned in square meters. ```Objective-C #import #import @implementation GeometryUtils // 面积计算 - (void)calculateArea { // 矩形面积 CLLocationCoordinate2D leftTop = CLLocationCoordinate2DMake(39.920, 116.400); CLLocationCoordinate2D rightBottom = CLLocationCoordinate2DMake(39.910, 116.410); double rectArea = BMKAreaBetweenCoordinates(leftTop, rightBottom); NSLog(@"矩形面积: %.2f 平方米", rectArea); // 多边形面积 CLLocationCoordinate2D polygon[4] = { {39.920, 116.400}, {39.920, 116.410}, {39.910, 116.410}, {39.910, 116.400} }; double polygonArea = BMKAreaForPolygon(polygon, 4); NSLog(@"多边形面积: %.2f 平方米", polygonArea); } @end ``` -------------------------------- ### Display and Configure BMKMapView Source: https://context7.com/baidulbs/baidumapkit/llms.txt Configures and displays the BMKMapView, the core view for map interactions. This includes setting map types, center coordinates, zoom levels, rotation, overlooking angles, enabling/disabling various map features like traffic and 3D buildings, and managing gestures. ```Objective-C #import #import @interface MapViewController () @property (nonatomic, strong) BMKMapView *mapView; @end @implementation MapViewController - (void)viewDidLoad { [super viewDidLoad]; // 创建地图视图 self.mapView = [[BMKMapView alloc] initWithFrame:self.view.bounds]; self.mapView.delegate = self; [self.view addSubview:self.mapView]; // 设置地图类型 self.mapView.mapType = BMKMapTypeStandard; // 标准地图 // self.mapView.mapType = BMKMapTypeSatellite; // 卫星地图 // 设置地图中心点(北京天安门坐标) CLLocationCoordinate2D center = CLLocationCoordinate2DMake(39.915, 116.404); [self.mapView setCenterCoordinate:center animated:YES]; // 设置缩放级别(4-21级) self.mapView.zoomLevel = 15; self.mapView.minZoomLevel = 4; self.mapView.maxZoomLevel = 21; // 设置地图旋转角度(-180~180度) self.mapView.rotation = 0; // 设置俯视角度(-45~0度) self.mapView.overlooking = -20; // 开启/关闭地图功能 self.mapView.buildingsEnabled = YES; // 3D 楼块效果 self.mapView.trafficEnabled = YES; // 路况图层 self.mapView.baiduHeatMapEnabled = NO; // 百度热力图 self.mapView.showMapPoi = YES; // 底图 POI 标注 // 手势控制 self.mapView.zoomEnabled = YES; // 缩放手势 self.mapView.scrollEnabled = YES; // 拖动手势 self.mapView.rotateEnabled = YES; // 旋转手势 self.mapView.overlookEnabled = YES; // 俯视手势 // 显示比例尺和指南针 self.mapView.showMapScaleBar = YES; self.mapView.mapScaleBarPosition = CGPointMake(10, 60); self.mapView.logoPosition = BMKLogoPositionLeftBottom; self.mapView.compassPosition = CGPointMake(10, 100); } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.mapView viewWillAppear]; self.mapView.delegate = self; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.mapView viewWillDisappear]; self.mapView.delegate = nil; } #pragma mark - BMKMapViewDelegate - (void)mapViewDidFinishLoading:(BMKMapView *)mapView { NSLog(@"地图加载完成"); } - (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated reason:(BMKRegionChangeReason)reason { NSLog(@"地图区域改变,中心点: %.6f, %.6f", mapView.centerCoordinate.latitude, mapView.centerCoordinate.longitude); } - (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate { NSLog(@"点击地图空白处: %.6f, %.6f", coordinate.latitude, coordinate.longitude); } - (void)mapview:(BMKMapView *)mapView onLongClick:(CLLocationCoordinate2D)coordinate { NSLog(@"长按地图: %.6f, %.6f", coordinate.latitude, coordinate.longitude); } // 地图截图 - (void)takeMapSnapshot { UIImage *snapshot = [self.mapView takeSnapshot]; UIImageWriteToSavedPhotosAlbum(snapshot, nil, nil, nil); } @end ``` -------------------------------- ### Handle Walking Route Results in Objective-C Source: https://context7.com/baidulbs/baidumapkit/llms.txt Callback function to process the results of a walking route search. It logs the distance and estimated duration if a route is found successfully. ```Objective-C // 步行路线结果 - (void)onGetWalkingRouteResult:(BMKRouteSearch *)searcher result:(BMKWalkingRouteResult *)result errorCode:(BMKSearchErrorCode)error { if (error == BMK_SEARCH_NO_ERROR && result.routes.count > 0) { BMKWalkingRouteLine *route = result.routes.firstObject; NSLog(@"步行距离: %d 米,预计时间: %d 秒", route.distance, route.duration); } } ``` -------------------------------- ### Handle Riding Route Results in Objective-C Source: https://context7.com/baidulbs/baidumapkit/llms.txt Handles the response from a cycling route search request. It logs the distance and estimated time for the first route found, if the search was successful. ```Objective-C // 骑行路线结果 - (void)onGetRidingRouteResult:(BMKRouteSearch *)searcher result:(BMKRidingRouteResult *)result errorCode:(BMKSearchErrorCode)error { if (error == BMK_SEARCH_NO_ERROR && result.routes.count > 0) { BMKRidingRouteLine *route = result.routes.firstObject; NSLog(@"骑行距离: %d 米,预计时间: %d 秒", route.distance, route.duration); } } ``` -------------------------------- ### Search Public Transit Route in Objective-C Source: https://context7.com/baidulbs/baidumapkit/llms.txt Calculates public transit routes, supporting both intra-city and inter-city travel. Users can specify preferences for transit policies, such as recommending routes within the city or prioritizing time for inter-city travel. ```Objective-C // 公共交通路线规划(支持跨城) - (void)searchMassTransitRoute { BMKMassTransitRoutePlanOption *option = [[BMKMassTransitRoutePlanOption alloc] init]; BMKPlanNode *from = [[BMKPlanNode alloc] init]; from.pt = CLLocationCoordinate2DMake(39.915, 116.404); from.cityName = @"北京"; option.from = from; BMKPlanNode *to = [[BMKPlanNode alloc] init]; to.pt = CLLocationCoordinate2DMake(31.230, 121.470); to.cityName = @"上海"; option.to = to; // 跨城交通方式偏好 option.incityPolicy = BMK_MASS_TRANSIT_INCITY_RECOMMEND; // 市内推荐 option.intercityPolicy = BMK_MASS_TRANSIT_INTERCITY_TIME_FIRST; // 跨城时间优先 [self.routeSearch massTransitSearch:option]; } ``` -------------------------------- ### Distance Calculation with BMKGeometry Source: https://context7.com/baidulbs/baidumapkit/llms.txt Provides functions to calculate the distance between two points in meters and the shortest distance from a point to a line segment. It also includes a function to find the foot of the perpendicular from a point to a line. ```Objective-C #import #import @implementation GeometryUtils // 距离计算 - (void)calculateDistance { CLLocationCoordinate2D coord1 = CLLocationCoordinate2DMake(39.915, 116.404); CLLocationCoordinate2D coord2 = CLLocationCoordinate2DMake(39.920, 116.450); BMKMapPoint point1 = BMKMapPointForCoordinate(coord1); BMKMapPoint point2 = BMKMapPointForCoordinate(coord2); // 两点之间的距离(米) CLLocationDistance distance = BMKMetersBetweenMapPoints(point1, point2); NSLog(@"两点距离: %.2f 米", distance); // 点到线段的距离 BMKMapPoint lineStart = BMKMapPointForCoordinate(CLLocationCoordinate2DMake(39.910, 116.400)); BMKMapPoint lineEnd = BMKMapPointForCoordinate(CLLocationCoordinate2DMake(39.920, 116.410)); CLLocationDistance distToLine = BMKGetDistanceFromPointToLine(point1, lineStart, lineEnd); NSLog(@"点到线距离: %.2f 米", distToLine); // 获取垂足点 BMKMapPoint footPoint = BMKGetPointToTheVerticalFootOfLine(point1, lineStart, lineEnd); CLLocationCoordinate2D footCoord = BMKCoordinateForMapPoint(footPoint); NSLog(@"垂足坐标: %.6f, %.6f", footCoord.latitude, footCoord.longitude); } @end ``` -------------------------------- ### Search Driving Route in Objective-C Source: https://context7.com/baidulbs/baidumapkit/llms.txt Performs driving route planning between two points, with optional waypoints. It allows customization of route policies such as time, distance, or toll preferences. The results include distance, duration, and toll information. ```Objective-C // 驾车路线规划 - (void)searchDrivingRoute { BMKDrivingRoutePlanOption *option = [[BMKDrivingRoutePlanOption alloc] init]; // 起点 BMKPlanNode *startNode = [[BMKPlanNode alloc] init]; startNode.pt = CLLocationCoordinate2DMake(39.915, 116.404); startNode.cityName = @"北京"; option.from = startNode; // 终点 BMKPlanNode *endNode = [[BMKPlanNode alloc] init]; endNode.pt = CLLocationCoordinate2DMake(39.995, 116.470); endNode.cityName = @"北京"; option.to = endNode; // 途经点(可选,最多5个) BMKPlanNode *waypoint = [[BMKPlanNode alloc] init]; waypoint.pt = CLLocationCoordinate2DMake(39.950, 116.440); option.wayPointsArray = @[waypoint]; // 驾车策略 option.drivingPolicy = BMK_DRIVING_TIME_FIRST; // 时间优先 // BMK_DRIVING_BLK_FIRST: 躲避拥堵 // BMK_DRIVING_DIS_FIRST: 距离优先 // BMK_DRIVING_FEE_FIRST: 少走高速 [self.routeSearch drivingSearch:option]; } ``` -------------------------------- ### Manage Map Annotations Source: https://context7.com/baidulbs/baidumapkit/llms.txt Methods to add, remove, and configure point annotations on the map view. ```APIDOC ## OBJECTIVE-C BMKPointAnnotation API ### Description This API allows developers to place point annotations on the map, customize their appearance using BMKPinAnnotationView, and handle lifecycle events via BMKMapViewDelegate. ### Method Objective-C Class Methods ### Parameters #### BMKPointAnnotation Properties - **coordinate** (CLLocationCoordinate2D) - Required - The latitude and longitude of the annotation. - **title** (NSString) - Optional - The main title displayed in the callout. - **subtitle** (NSString) - Optional - The subtitle displayed in the callout. ### Implementation Example ```objectivec // Create and add an annotation BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc] init]; annotation.coordinate = CLLocationCoordinate2DMake(39.915, 116.404); annotation.title = @"Tiananmen"; [self.mapView addAnnotation:annotation]; ``` ### Delegate Methods - **viewForAnnotation**: Returns the view to be displayed for a given annotation. - **clickAnnotationView**: Triggered when a user taps an annotation. - **didSelectAnnotationView**: Triggered when an annotation is selected. - **didChangeDragState**: Triggered when an annotation is dragged by the user. ``` -------------------------------- ### Handle Driving Route Results in Objective-C Source: https://context7.com/baidulbs/baidumapkit/llms.txt Processes the results of a driving route search. It logs the number of routes found and iterates through each route to extract details like distance, duration, and toll. It also shows how to access step-by-step navigation instructions. ```Objective-C #pragma mark - BMKRouteSearchDelegate // 驾车路线结果 - (void)onGetDrivingRouteResult:(BMKRouteSearch *)searcher result:(BMKDrivingRouteResult *)result errorCode:(BMKSearchErrorCode)error { if (error == BMK_SEARCH_NO_ERROR) { NSLog(@"驾车路线规划成功,共 %lu 条路线", (unsigned long)result.routes.count); for (BMKDrivingRouteLine *route in result.routes) { NSLog(@"距离: %d 米", route.distance); NSLog(@"时间: %d 秒", route.duration); NSLog(@"路费: %@", route.toll); // 获取路线上的点绑制折线 NSMutableArray *points = [NSMutableArray array]; for (BMKDrivingStep *step in route.steps) { for (int i = 0; i < step.pointsCount; i++) { BMKMapPoint point = step.points[i]; CLLocationCoordinate2D coord = BMKCoordinateForMapPoint(point); // 将坐标点添加到数组 } NSLog(@"导航指令: %@", step.instruction); } } } else { NSLog(@"驾车路线规划失败: %d", error); } } ``` -------------------------------- ### Coordinate Conversion API Source: https://context7.com/baidulbs/baidumapkit/llms.txt Provides methods to convert between various coordinate systems including GPS, GCJ02, and BD09LL, as well as projections into map points and mercator coordinates. ```APIDOC ## BMKCoordTrans ### Description Converts coordinates between different systems (GPS, GCJ02, BD09LL). ### Method Function Call ### Parameters - **coordinate** (CLLocationCoordinate2D) - Required - The source coordinate to convert. - **sourceType** (BMK_COORDTYPE) - Required - The source coordinate system type. - **destType** (BMK_COORDTYPE) - Required - The target coordinate system type. ### Response - **result** (CLLocationCoordinate2D) - The converted coordinate in the target system. ```