Get distance between two location from CLLocation
Get distance |
如果今天我們要做到現在使用者距離這些地標各別距離有多遠,如果可以把這些資訊顯示出來,一定可以帶給使用者很有感覺,對於要找這些地標可以做出更好兩點概念。那麼我們要如何求出座標兩點距離呢?
這概念要從兩點經緯度來看,而在 Google search 座標距離,網路上也蠻多公式在求計算這些距離位置。回到我們的 iPhone app 上要怎麼求呢?很慶幸的是 Cocoa 已經有內建,從 CLLocation 有提供換算的 method。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
double distanceKM = 0; | |
CLLocation *currentLocation = [[CTLocationManager sharedInstance] | |
currentLocation]; | |
CLLocation *itemLocation = [[CLLocation alloc] | |
initWithLatitude:item.coordinate.latitude longitude: | |
item.coordinate.longitude]; | |
if ([currentLocation respondsToSelector: @selector( | |
distanceFromLocation:)]) { | |
CLLocationDistance distanceResult = | |
[currentLocation distanceFromLocation: itemLocation]; | |
distanceKM = distanceResult / 1000; | |
} else if ([currentLocation respondsToSelector: | |
@selector(getDistanceFrom:)]) { | |
CLLocationDistance distanceResult = [currentLocation getDistanceFrom: | |
itemLocation]; | |
distanceKM = distanceResult / 1000; | |
} | |
NSString *distanceInformation = [NSString stringWithFormat: | |
@"距離%.2f公里", distanceKM]; |
從 CLLocation 在 iPhone 3.2 版以前要用 - (CLLocationDistance)getDistanceFrom:(const CLLocation *)location,但是目前已經 Deprecated 了,而在 iPhone 3.2 版之後可以用 - (CLLocationDistance)distanceFromLocation:(const CLLocation *)location。而判斷有沒有支援可以使用 is response to 來做呼叫錢的判定。
所以透過這樣取,可以拿到 CLLocationDistance,他是以公尺來做單位。所以如果今天要顯示距離多少公里要稍微換算一下,最後我們記得到距離有多少公里。再將它們一一顯示在 Map view 上面的 MKAnnotationView 即可。
Comments
Post a Comment