8/02/2009

[iPhone程式]如何取得使用者目前的座標位置?

☉目標:在iPhone應用程式中取得使用者目前的經緯度。

☉效果畫面:
這裡借用了http://iphone4.tw的圖片。自己懶得Print Screen...XD
03
我們可以透過CLLocationManager類別取得使用者座標位置。
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];

☉步驟說明:

Step(1):首先,先建立一個CLLocationManager類別的物件。


Step(2):接著指定委派的對象,這裡是指定自己(self)。





Step(3):最後呼叫CLLocationManager類別的一個方法「startUpdatingLocation」,這個時候如果使用者是第一次使用你的iPhone軟體,iPhone就會詢問使用者是否允許iPhone軟體取得使用者座標。





Step(4):當你點選確定後,iPhone就會開始定位,定位完成後就會觸發「didUpdateToLocation」事件。











因此,當定位完成你可以用以下方法取得使用者座標後,接著進行一些處理。

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{

NSString *userLat = [[NSNumber numberWithDouble:newLocation.coordinate.latitude] stringValue];
NSString *userLng = [[NSNumber numberWithDouble:newLocation.coordinate.longitude] stringValue];
}

5 意見:

李先生 提到...

請否請教
locationManager.delegate = self;
指派給自己的目的和好處為何?

finalevil 提到...

我沒記錯的話...
沒有這一行locationManager就無法自動update現在的location

李先生 提到...

Thank you.
指派給自己的意思是什麼呢?
一般利用delegate別人來獲得別人的能力
但是這裡把delegate自己,是因為想用自己的能力是嗎?

finalevil 提到...

這篇文章寫的不錯,可以參考,
http://zonble.net/archives/2009_11/1245.php

我的理解跟你一樣,delegate其實就是告訴一個object遇到某些事情的時候要怎麼處理,所以當指定自己(self)做為delegate的對象時,事情發生的時候,自己可以處理這件事情(自己有能力處理)。

李先生 提到...

謝謝你 zonble的文章內容很不錯,不過需要時間消化一下,

張貼意見