iOS開發中最基本的位置功能實現樣本_IOS

來源:互聯網
上載者:User

定位擷取位置及位置編碼-反編碼
我們的應用程式,可以通過添加Core Location架構所包含的類,擷取裝置的地圖位置。
添加CoreLocation.framework架構,匯入#import<CoreLocation/CoreLocation.h>。
使用地圖服務時,會消耗更多地裝置電量.因此,在擷取到裝置的位置後,應該停止定位來節省電量。
我們通過一個demo來展示內容與效果

複製代碼 代碼如下:

//
// HMTRootViewController.h
// My-GPS-Map
//
// Created by hmt on 14-4-12.
// Copyright (c) 2014年 胡明濤. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface HMTRootViewController : UIViewController <CLLocationManagerDelegate>

@end

//
// HMTRootViewController.m
// My-GPS-Map
//
// Created by hmt on 14-4-12.
// Copyright (c) 2014年 胡明濤. All rights reserved.
//

#import "HMTRootViewController.h"
#import <AddressBook/AddressBook.h>

@interface HMTRootViewController (){

CLLocationManager * _locationManage;
}

@property (nonatomic,retain) CLLocationManager * locationManage;

@end

@implementation HMTRootViewController

- (void)dealloc{

RELEASE_SAFELY(_locationManage);
[super dealloc];

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.

[self createGPSMap];
self.view.backgroundColor = [UIColor redColor];

}

- (void)createGPSMap{

// 初始化位置服務
self.locationManage = [[CLLocationManager alloc]init];

// 要求CLLocationManager對象返回全部資訊
_locationManage.distanceFilter = kCLDistanceFilterNone;

// 設定定位精度
_locationManage.desiredAccuracy = kCLLocationAccuracyBest;

// 設定代理
_locationManage.delegate = self;

// 開始定位
[_locationManage startUpdatingLocation];

[_locationManage release];

}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{

CLLocation * newLocation = [locations lastObject];
// 停止即時定位
[_locationManage stopUpdatingLocation];

// 取得經緯度
CLLocationCoordinate2D coord2D = newLocation.coordinate;
double latitude = coord2D.latitude;
double longitude = coord2D.longitude;
NSLog(@"緯度 = %f 經度 = %f",latitude,longitude);

// 取得精度
CLLocationAccuracy horizontal = newLocation.horizontalAccuracy;
CLLocationAccuracy vertical = newLocation.verticalAccuracy;
NSLog(@"水平方 = %f 垂直方 = %f",horizontal,vertical);

// 取得高度
CLLocationDistance altitude = newLocation.altitude;
NSLog(@"%f",altitude);

// 取得此時時刻
NSDate *timestamp = [newLocation timestamp];
// 執行個體化一個NSDateFormatter對象
NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
// 設定時間格式
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss a"];
[dateFormat setAMSymbol:@"AM"]; // 顯示中文, 改成"上午"
[dateFormat setPMSymbol:@"PM"];
// 求出當天的時間字串,當更改時間格式時,時間字串也能隨之改變
NSString *dateString = [dateFormat stringFromDate:timestamp];
NSLog(@"此時此刻時間 = %@",dateString);


// -----------------------------------------位置反編碼--------------------------------------------
CLGeocoder * geocoder = [[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {

for (CLPlacemark * place in placemarks) {

NSLog(@"name = %@",place.name); // 位置名
NSLog(@"thoroughfare = %@",place.thoroughfare); // 街道
NSLog(@"subAdministrativeArea = %@",place.subAdministrativeArea); // 子街道
NSLog(@"locality = %@",place.locality); // 市
NSLog(@"subLocality = %@",place.subLocality); // 區
NSLog(@"country = %@",place.country); // 國家

NSArray *allKeys = place.addressDictionary.allKeys;
for (NSString *key in allKeys)
{
NSLog(@"key = %@, value = %@",key, place.addressDictionary[key]);
}
#pragma mark - 使用系統定義的字串直接查詢,記得匯入AddressBook架構
NSLog(@"kABPersonAddressCityKey = %@", (NSString *)kABPersonAddressCityKey);
NSLog(@"city = %@", place.addressDictionary[(NSString *)kABPersonAddressCityKey]);
NSString *city = place.locality;
if(city == nil)
{
city = place.addressDictionary[(NSString *)kABPersonAddressStateKey];
}
}
}];
}


- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

程式運行結果:(以39.3,116.4為例)

複製代碼 代碼如下:

//  判斷輸入的地址 
if (self.locationTextField.text == nil  ||  [self.locationTextField.text length] == 0) { 
    return; 

 
CLGeocoder *geocoder = [[CLGeocoder alloc] init]; 
/*  -----------------------------------------位置編碼--------------------------------------------  */ 
[geocoder geocodeAddressString:_locationTextField.text completionHandler:^(NSArray *placemarks, NSError *error) { 
     
    for (CLPlacemark *placemark in placemarks) { 
         
        CLLocationCoordinate2D coordinate = placemark.location.coordinate; 
        NSString *strCoordinate = [NSString stringWithFormat:@"緯度 = %3.5f\n 經度 = %3.5f",coordinate.latitude,coordinate.longitude]; 
        NSLog(@"%@",strCoordinate); 
        NSDictionary *addressDictionary = placemark.addressDictionary; 
        NSString *address = [addressDictionary objectForKey:(NSString *)kABPersonAddressStreetKey]; 
        NSString *state = [addressDictionary objectForKey:(NSString *)kABPersonAddressStateKey]; 
        NSString *city = [addressDictionary objectForKey:(NSString *)kABPersonAddressCityKey]; 
        NSLog(@"街道 = %@\n 省 = %@\n 城市 = %@",address,state,city); 
    } 
}]; 

地圖的使用以及標註地圖
使用CoreLocation架構擷取了當前裝置的位置,這一章介紹地圖的使用。
首先,匯入<MapKit.framework>架構:

複製代碼 代碼如下:

#import <MapKit/MapKit.h>

main程式碼範例

複製代碼 代碼如下:

main.h 
 
#import <UIKit/UIKit.h> 
#import <MapKit/MapKit.h> 
//  引用地圖協議 
@interface HMTMainViewController : UIViewController<MKMapViewDelegate> 
 
@end 
 
main.m 
 
// 
//  HMTMainViewController.m 
//  Map 
// 
//  Created by HMT on 14-6-21. 
//  Copyright (c) 2014年 humingtao. All rights reserved. 
// 
 
#import "HMTMainViewController.h" 
#import "HMTAnnotation.h" 
 
@interface HMTMainViewController () 
 
@property (nonatomic ,strong) MKMapView *mapView; 
 
@end 
 
@implementation HMTMainViewController 
 
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
        // Custom initialization 
    } 
    return self; 

 
- (void)viewDidLoad 
 

     
    [super viewDidLoad]; 
    self.view.backgroundColor = [UIColor redColor]; 
     
    // Do any additional setup after loading the view. 
     
    self.navigationItem.title = @"地表徵圖注"; 
    self.mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)]; 
     
    //  是否顯示使用者當前位置 
    self.mapView.showsUserLocation = YES; 
    //  設定代理 
    self.mapView.delegate = self; 
     
    //  地圖顯示類型 
    /**
     *      MKMapTypeStandard = 0, //  標準地圖
     *      MKMapTypeSatellite,    //  衛星地圖
     *      MKMapTypeHybrid        //  混合地圖
     */ 
    self.mapView.mapType = MKMapTypeStandard; 
    //  經緯度 
    CLLocationCoordinate2D coord2D = {39.910650,116.47030}; 
    //  顯示範圍,數值越大,範圍就越大 
    MKCoordinateSpan span = {0.1,0.1}; 
    //  顯示地區 
    MKCoordinateRegion region = {coord2D,span}; 
    //  給地圖設定顯示地區 
    [self.mapView setRegion:region animated:YES]; 
    //  是否允許縮放 
    //self.mapView.zoomEnabled = NO; 
    //  是否允許滾動 
    //self.mapView.scrollEnabled = NO; 
 
    //  初始化自訂Annotation(可以設定多個) 
    HMTAnnotation *annotation = [[HMTAnnotation alloc] initWithCGLocation:coord2D]; 
    //  設定標題 
    annotation.title = @"自訂標註位置"; 
    //  設定子標題 
    annotation.subtitle = @"子標題"; 
    //  將標註添加到地圖上(執行這步,就會執行下面的代理方法viewForAnnotation) 
    [self.mapView addAnnotation:annotation]; 
     
    [self.view addSubview:_mapView]; 
     

 
//   返回標註視圖(圖釘視圖) 
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{ 
 
    /**
     *  是不是有點像自訂UITableViewCell一樣
     */ 
    static NSString *identifier = @"annotation"; 
    //  複用標註視圖(MKPinAnnotationView是圖釘視圖,繼承自MKAnnotation) 
    MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier]; 
    if (annotationView == nil) { 
        annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier]; 
    } 
    //  判斷是否為自訂的標註視圖 
    if ([annotation isKindOfClass:[HMTAnnotation class]]) { 
         
        //  設定圖釘圓圈顏色 
        annotationView.pinColor = MKPinAnnotationColorGreen; 
        //  點擊頭針紅色圓圈是否顯示上面設定好的標題視圖 
        annotationView.canShowCallout = YES; 
        //  要自訂錨點圖片,可考慮使用MKAnnotationView;MKPinAnnotationView只能是以圖釘形式顯示!!!! 
        annotationView.image = [UIImage imageNamed:@"customImage"]; 
        //  添加標題視圖右邊視圖(還有左邊視圖,具體可自行查看API) 
        UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; 
        [button addTarget:self action:@selector(didClickAnnotationViewRightButtonAction:) forControlEvents:UIControlEventTouchUpInside]; 
        annotationView.rightCalloutAccessoryView = button; 
        //  是否以動畫形式顯示標註(從天而降) 
        annotationView.animatesDrop = YES; 
        annotationView.annotation = annotation; 
         
        //  返回自訂的標註視圖 
        return annotationView; 
         
    }else{ 
        
        //  當前裝置位置的標註視圖,返回nil,當前位置會建立一個預設的標註視圖 
        return nil; 
    } 
     

 
- (void)didClickAnnotationViewRightButtonAction:(UIButton *)button{ 
 
    NSLog(@"%d %s",__LINE__,__FUNCTION__); 

 
//  更新當前位置調用 
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{ 
 
    NSLog(@"%d %s",__LINE__,__FUNCTION__); 

 
//  選中標註視圖 
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{ 
     
    NSLog(@"%d %s",__LINE__,__FUNCTION__); 

 
//  地圖的現實地區改變了調用 
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{ 
 
    NSLog(@"%d %s",__LINE__,__FUNCTION__); 

 
- (void)didReceiveMemoryWarning 

    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 

 
@end 

自訂MKAnnotationView

複製代碼 代碼如下:

#import <Foundation/Foundation.h> 
#import <MapKit/MapKit.h> 
//  引入MKAnnotation協議,切記不能忘記!!!!!!!!! 
@interface HMTAnnotation : NSObject<MKAnnotation> 
 
@property (nonatomic,readonly) CLLocationCoordinate2D coordinate;  //  座標 
@property (nonatomic,copy) NSString *title;     //  位置名稱 
@property (nonatomic,copy) NSString *subtitle;  //  位置子資訊(可選) 
 
- (id)initWithCGLocation:(CLLocationCoordinate2D) coordinate; 
 
@end 
 
#import "HMTAnnotation.h" 
 
@implementation HMTAnnotation 
 
- (id)initWithCGLocation:(CLLocationCoordinate2D)coordinate{ 
 
    if (self = [super init]) { 
         
        _coordinate = coordinate; 
    } 
    return self; 

 
@end 

效果圖:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.