我有距離型CLLocationDistance的變量,我需要將其轉換在整型變量我怎麼能做到這一點CLLocationDistance轉換
我必須使用
CLLocationDistance kilometers;
int distance = [kilometers intValue];
但它給錯誤。
幫助傢伙
我有距離型CLLocationDistance的變量,我需要將其轉換在整型變量我怎麼能做到這一點CLLocationDistance轉換
我必須使用
CLLocationDistance kilometers;
int distance = [kilometers intValue];
但它給錯誤。
幫助傢伙
distanceFromLocation:
返回從接收器的位置到指定位置的距離(以米爲單位)。
- (CLLocationDistance)distanceFromLocation:(const CLLocation *)location
參數
位置的其他位置。
返回值 兩個位置之間的距離(以米爲單位)。
返回類型是double
而不是int
。而且它不是NSNumber
。
爲了澄清,因爲它是一個Double(一個內部類型,而不是一個對象),所以沒有[intValue]方法可以運行。既然你願意失去準確性,只需分配值。如果您想要將其舍入,只需添加.5,然後分配它。 – KevinDTimm 2011-02-03 16:01:00
這將通過使用CLLocationDistance
來計算兩個位置之間的距離。默認情況下,它以米爲單位給出值。要轉換爲公里,請將CLLocationDistance/1000.0
分開。要獲得英里數乘以CLLocationDistance*0.62137
。
//Pass your current location Latitude and longitude
CLLocation *currentlocation = [[CLLocation alloc] initWithLatitude:13.015370f longitude:80.200393f];
//Pass your destination location Latitude and longitude
CLLocation *destination = [[CLLocation alloc] initWithLatitude:37.420948f longitude:-122.09578499999998f];
CLLocationDistance meters = [currentlocation distanceFromLocation:destination];
//get distance in meters
NSLog(@"meters :%f", meters);
//get distance in kilometers
CLLocationDistance kilometers = meters/1000.0;
NSLog(@"kilometers :%f", kilometers);
//Get distance in miles
NSLog(@"Miles:%f",kilometers*0.62137);
//convert kilometers to int value
int num=kilometers;
請添加說明以改善答案;不鼓勵代碼的答案!謝謝! – namezero 2015-08-10 10:10:08
斯威夫特:
var initialLocation :CLLocation?
var updatedUserLocation :CLLocation?
var distanceBetweenLocations: CLLocationDistance?
//MK MapView Delegate
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
updatedUserLocation = locations.last
distanceBetweenLocations = updatedUserLocation!.distanceFromLocation(initialLocation!)
//convert To Miles
distanceBetweenLocations = Utility.convertCLLocationDistanceToMiles(distanceBetweenLocations)
//Setting Distance Value
distanceLabel.text = String(format: " Distance : %.2f ", distanceBetweenLocations!)
}
注:我有類命名工具,供應整個項目的公共類的方法。這是爲了更好地實現代碼的可重用性和減少。
// Utility.swift
import UIKit
import Foundation
import CoreLocation
class Utility {
class func convertCLLocationDistanceToMiles (var targetDistance : CLLocationDistance?) -> CLLocationDistance {
targetDistance = targetDistance!*0.00062137
return targetDistance!
}
class func convertCLLocationDistanceToKiloMeters (var targetDistance : CLLocationDistance?) -> CLLocationDistance {
targetDistance = targetDistance!/1000
return targetDistance!
}
}
SWIFT 4
末到本黨,但你也可以創建一個這樣的擴展:
CLLocationDistance.swift
import UIKit
import CoreLocation
extension CLLocationDistance {
func inMiles() -> CLLocationDistance {
return self*0.00062137
}
func inKilometers() -> CLLocationDistance {
return self/1000
}
}
你可以稱它爲如下:
distance.inKilometers()
我希望這可以幫助任何人絆倒在這!
您收到的錯誤可能對(其他人)有幫助。請包括它。 – KevinDTimm 2011-02-03 16:01:26