百度地圖demo (定位到當前城市,並加入定制大頭針)


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;
}

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM