PS :因为百度API 官方提供的demo已经够详细了、为何我还需要写这篇demo ?也许是因为我刚接触百度地图的时候,总有些细节被忽略,以至于造成停滞不前,浪费些时间。故此写下此篇启程之文,望大批一众第一战线的队友不至于因为一些基本的东西而停住了脚步。
话不多说,就此开始吧!!
百度地图API http://dev.baidu.com/wiki/imap/index.php?title=iOS平台/相关下载
具体操作可以参考百度api ,非常的详细。此处说点注意事项
1——若为模拟机版本 ,应该导入模拟版的.a文件。
2——关于Object++ 的解决问题,此处的解决方式为 ,将一.m文件 的后缀名改为.mm文件。
3——需要在工程属性中显式设定:在 XCode 的 Project -> Edit Active Target -> Build -> Linking -> Other Linker Flags 中添加-all_load

然后获取自己的API KEY,具体方法按百度的官网申请就行,比较简单。
下载的文件应该有三个
AppDelegate.h
#import <UIKit/UIKit.h>
#import "BMapKit.h"
@class ViewController;
@interface AppDelegate : UIResponder <UIApplicationDelegate,BMKGeneralDelegate>
{
BMKMapManager* _mapManager;
}
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ViewController *viewController;
@end
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// 要使用百度地图,请先启动BaiduMapManager
_mapManager = [[BMKMapManager alloc]init];
BOOL ret = [_mapManager start:@"BBD534723EDA85155BE4AD4B2BF59DA97F2725D9" generalDelegate:nil];
if (!ret) {
NSLog(@"manager start failed!");
}
// Override point for customization after application launch.
self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
ViewController.h
#import <UIKit/UIKit.h>
#import "BMapKit.h"
@interface ViewController : UIViewController<BMKMapViewDelegate,BMKSearchDelegate>
{
BMKMapView *mymapView;
//定位
NSMutableArray *pathArray;
// annotation
BMKPointAnnotation* myAnnotation;
//搜索
BMKSearch* _search;//搜索要用到的
UITextField *destinationText;
CLLocationCoordinate2D startPt;
//
float localLatitude;
float localLongitude;
//定位的城市名字
NSString *cityStr;
NSString *cityName;
NSString *province;
}
@property (nonatomic, retain) BMKMapView* mymapView;
@end
ViewController.m
#import "ViewController.h"
#import "MyControl.h"
#define MYBUNDLE_NAME @ "mapapi.bundle"
#define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
#define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]
BOOL isRetina = FALSE;
//搜索
@interface RouteAnnotation : BMKPointAnnotation
{
int _type; ///<0:起点 1:终点 2:公交 3:地铁 4:驾乘
int _degree;
}
@property (nonatomic) int type;
@property (nonatomic) int degree;
@end
#pragma mark -image
@interface UIImage(InternalMethod)
- (UIImage*)imageRotatedByDegrees:(CGFloat)degrees;
@end
@implementation UIImage(InternalMethod)
- (UIImage*)imageRotatedByDegrees:(CGFloat)degrees
{
CGSize rotatedSize = self.size;
if (isRetina) {
rotatedSize.width *= 2;
rotatedSize.height *= 2;
}
UIGraphicsBeginImageContext(rotatedSize);
CGContextRef bitmap = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
CGContextRotateCTM(bitmap, degrees * M_PI / 180);
CGContextRotateCTM(bitmap, M_PI);
CGContextScaleCTM(bitmap, -1.0, 1.0);
CGContextDrawImage(bitmap, CGRectMake(-rotatedSize.width/2, -rotatedSize.height/2, rotatedSize.width, rotatedSize.height), self.CGImage);
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
@end
@implementation ViewController
@synthesize mymapView;
//获取图片资源用:
- (NSString*)getMyBundlePath1:(NSString *)filename
{
NSBundle * libBundle = MYBUNDLE ;
if ( libBundle && filename ){
NSString * s=[[libBundle resourcePath ] stringByAppendingPathComponent : filename];
NSLog ( @"%@" ,s);
return s;
}
return nil ;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
myAnnotation = [[BMKPointAnnotation alloc]init];
//用来记录路线信息的,以后会用到
pathArray=[[NSMutableArray array] retain];
//
destinationText = [MyControl createTextFieldWithFrame:CGRectMake(10, 10, 200, 20) Placeholder:@"destination"];
destinationText.text = @"新中关";
[self.view addSubview:destinationText];
_search = [[BMKSearch alloc]init];
mymapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 92, 320, 480)];
[mymapView setMapType:BMKMapTypeStandard];
//启动定位
mymapView.showsUserLocation = YES;
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(39.89288,116.416626);
// 缩放
BMKCoordinateSpan span = BMKCoordinateSpanMake(0.5, 0.5);
// 确定一个区域
BMKCoordinateRegion region = BMKCoordinateRegionMake(coordinate, span);
mymapView.region = region;
self.view = mymapView;
CGSize screenSize = [[UIScreen mainScreen] currentMode].size;
if (((screenSize.width >= 639.9f))
&& (fabs(screenSize.height >= 959.9f)))
{
isRetina = TRUE;
}
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
//设置 mapView 的 delegate 、_search 搜索的delegate
mymapView.delegate = self;
_search.delegate = self;
}
#pragma mark - 定位
/**
*在地图View将要启动定位时,会调用此函数
*@param mapView 地图View
*/
- (void)mapViewWillStartLocatingUser:(BMKMapView *)mapView {
NSLog(@"start locate");
}
/**
*定位失败后,会调用此函数
*@param mapView 地图View
*@param error 错误号,参考CLError.h中定义的错误号
*/
- (void)mapView:(BMKMapView *)mapView didFailToLocateUserWithError:(NSError *)error {
if (error != nil) {
NSLog(@"local failed: %@",[error localizedDescription]);
}
NSLog(@"local failed");
}
/**
*用户位置更新后,会调用此函数
*@param mapView 地图View
*@param userLocation 新的用户位置
在实际使用中,只需要 [mapView setShowsUserLocation:YES]; mapView.delegate = self; 两句代码就可以启动下面的方法。疑问,为什么我的位置没有移动的情况下,这个方法循环被调用呢?
*/
- (void)mapView:(BMKMapView *)mapView didUpdateUserLocation:(BMKUserLocation *)userLocation {
if (userLocation != nil) {
NSLog(@"定位成功------纬度%f 经度%f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
}
localLatitude = userLocation.location.coordinate.latitude;
localLongitude = userLocation.location.coordinate.longitude;
CLLocationCoordinate2D coordinate = userLocation.location.coordinate;
// 缩放
BMKCoordinateSpan span = BMKCoordinateSpanMake(0.1, 0.1);
// 确定一个区域
BMKCoordinateRegion region = BMKCoordinateRegionMake(coordinate, span);
[mymapView setRegion:region animated:YES];
//把坐标传给startPt保存起来
startPt = (CLLocationCoordinate2D){0,0};
startPt = (CLLocationCoordinate2D){localLatitude,localLongitude};
[self performSelector:@selector(busSearch)];
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:localLatitude
longitude:localLongitude];
[geocoder reverseGeocodeLocation:loc completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark *placemark in placemarks) {
province = placemark.administrativeArea;
if (province.length == 0) {
province = placemark.locality;
cityName = placemark.subLocality;
NSLog(@"cityName %@",cityName);//获取城市名
NSLog(@"province %@ ++",province);
}else {
//获取街道地址
cityStr = placemark.thoroughfare;
//获取城市名
cityName = placemark.locality;
province = placemark.administrativeArea;
NSLog(@"city %@",cityStr);//获取街道地址
NSLog(@"cityName %@",cityName);//获取城市名
NSLog(@"province %@",province);
}
break;
}
CLLocationCoordinate2D coor;
coor.latitude = localLatitude;
coor.longitude = localLongitude;
myAnnotation.coordinate = coor;
myAnnotation.title = province;
NSLog(@"....%@",province);
myAnnotation.subtitle = cityName;
[mymapView addAnnotation:myAnnotation];
}];
// 一次定位
mymapView.showsUserLocation = NO;
}
#pragma mark - annotation (annotation)
/**
*根据anntation生成对应的View
*@param mapView 地图View
*@param annotation 指定的标注
*@return 生成的标注View
*/
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
BMKPinAnnotationView *newAnnotation = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
newAnnotation.canShowCallout = YES;
newAnnotation.pinColor = BMKPinAnnotationColorPurple;
newAnnotation.animatesDrop = YES;
newAnnotation.draggable = YES;
//custom newAnnotation View
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
view.backgroundColor = [UIColor redColor];
newAnnotation.leftCalloutAccessoryView = view;
[view release];
newAnnotation.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
return newAnnotation;
}
return nil;
}

