简体   繁体   English

如何计算我当前位置和MapView中其他Pins之间的距离

[英]How to calculate the distance between my current location and other Pins in MapView

I am new to Swift and I need to calculate the nearest places around my current location. 我是Swift的新手,我需要计算当前位置附近的最近地点。 Would you advice me which function should I use to calculate the distance between my location and the nearest around me. 您能建议我使用哪个函数来计算我的位置和附近的最近位置之间的距离。 I have to display the distance and the places in the app,so that the user can choose which one fits best for him.I think I should use latitude and longitude coordinates which can be compared with mine. 我必须在应用程序中显示距离和位置,以便用户可以选择最适合自己的位置。我认为我应该使用可以与我比较的纬度和经度坐标。 I also found out that I have to use distanceFromLocation , but I do not know how and I would be glad if someone provide me with an example which I can use for my code. 我还发现我必须使用distanceFromLocation,但是我不知道怎么做,如果有人为我提供一个可用于我的代码的示例,我将非常高兴。 My code so far is: 到目前为止,我的代码是:

 class ViewThree: UIViewController, CLLocationManagerDelegate{
@IBOutlet weak var SegmentControl: UISegmentedControl!
@IBOutlet weak var Mapview: MKMapView!


var manager =  CLLocationManager()
var receiveImeNaSladkarnica: String = ""
var KordaA: String = ""
var KordaB: String = ""
var PodImeNaObekt: String = ""

  override func viewDidLoad() {
super.viewDidLoad()


    let pinLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake((KordaA as NSString).doubleValue,(KordaB as NSString).doubleValue)
    let objectAnn = MKPointAnnotation()
    objectAnn.coordinate = pinLocation
    objectAnn.title = receiveImeNaSladkarnica
    objectAnn.subtitle = PodImeNaObekt
    self.Mapview.addAnnotation(objectAnn)

 }

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

@IBAction func Directions(sender: AnyObject) {
    UIApplication.sharedApplication().openURL(NSURL(string: "http://maps.apple.com/maps?daddr=\((KordaA as NSString).doubleValue),\((KordaB as NSString).doubleValue))")!)



}

@IBAction func MapType(sender: AnyObject) {
    if (SegmentControl.selectedSegmentIndex == 0){
        Mapview.mapType = MKMapType.Standard
    }
    if (SegmentControl.selectedSegmentIndex == 1){
        Mapview.mapType = MKMapType.Satellite
    }


}

@IBAction func LocateMe(sender: AnyObject) {
    manager.delegate = self
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()

    Mapview.showsUserLocation = true



}
func  locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userlocation: CLLocation = locations[0] as CLLocation
    manager.stopUpdatingLocation()
    let location = CLLocationCoordinate2D(latitude: userlocation.coordinate.latitude, longitude: userlocation.coordinate.longitude)
    let span = MKCoordinateSpanMake(0.5, 0.5)
    let region = MKCoordinateRegion(center: location, span: span)
    Mapview.setRegion(region, animated: true )
}

I had the same scenario with an other app. 我在其他应用程序中遇到了相同的情况。

Within the CLLocation object, there is an instance function: CLLocation对象中,有一个实例函数:

func distanceFromLocation(location: CLLocation) -> CLLocationDistance func distanceFromLocation(位置:CLLocation)-> CLLocationDistance

//Get your two locations that you want to calculate the distance from:

let userLocation: CLLocation = ...
let locationToCompare: CLLocation = ...

// Returned value is in meters
let distanceMeters = userLocation.distanceFromLocation(locationToCompare)

// If you want to round it to kilometers
let distanceKilometers = distanceMeters / 1000.00

// Display it in kilometers
let roundedDistanceKilometers = String(Double(round(100 * distanceKilometers) / 100)) + " km"

UPDATED 更新

For your use case 对于您的用例

let locations = ... // All locations you want to compare

for location in locations {

    let distanceMeters = userLocation.distanceFromLocation(location)

    if distanceMeters > 5000 { // Some distance filter
          // Don't display this location
    } else {
          // Display this location
    }

}

MY CODE: IMPROVED 我的代码:已改进

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let userlocation:CLLocation = locations[0] as CLLocation

    manager.stopUpdatingLocation()

    let location = CLLocationCoordinate2D(latitude: userlocation.coordinate.latitude, longitude: userlocation.coordinate.longitude)

    let span = MKCoordinateSpanMake(0.5, 0.5)

    let region = MKCoordinateRegion(center: location, span: span)

    Mapview.setRegion(region, animated: true)

    let locationStrings = ["42.6977,23.3219","43.6977,24.3219"]

    // This array must be an array that contains CLLocation objects        
    var locations: [CLLocation] = []

    // We must retrieve the latitude and longitude from locationStrings array to convert them into CLLocation objects
    for locationString in locationStrings {

        let location = CLLocation(latitude: <latitude_value>, longitude: <latitude_value>)

        locations.append(location)

    }

    // Then you will be able to enumerate through the array
    for location in locations {

        let distanceMeters = userLocation.distanceFromLocation(location)

        if distanceMeters > 5000 { // Some distance filter
            // Don't display this location
        } else {
            // Display this location
        }

    }

您可以使用distanceFromLocation方法获取距离

let distance = userlocation.distanceFromLocation(YourPinInMap)
  locA = [[CLLocation alloc] initWithLatitude:[[[NSUserDefaults standardUserDefaults]valueForKey:@"startLat"]floatValue] longitude:[[[NSUserDefaults standardUserDefaults]valueForKey:@"startlong"]floatValue]];


 locB = [[CLLocation alloc] initWithLatitude:[[[NSUserDefaults standardUserDefaults]valueForKey:@"destLat"]floatValue]  longitude:[[[NSUserDefaults standardUserDefaults]valueForKey:@"destLong"]floatValue]];


distance = [locA distanceFromLocation:locB];

where locA and locB are CLLocation type pass the lat long over there 其中locA和locB是CLLocation类型,将lat传递到那里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何计算当前位置与JSON文件中填充的位置之间的距离 - How to calculate the distance between my current location and locations populated in a JSON File 如何在iOS中通过Localsearch(搜索栏)计算当前位置与所选位置/目的地之间的距离 - How to calculate distance between current location and selected location/destination from Localsearch (search bar) in iOS MapView没有显示位置和图钉? - MapView not showing location and Pins? 在iOS中的固定点和我当前位置之间行走时计算距离 - Calculate distance while walking between a fixed point and my current location in iOS 如何计算用户当前位置和多个地理坐标之间的最短距离 - How to calculate shortest distance between user current location and multiple geo coordinate 计算我的位置和 Swift 上的 MapKit 引脚之间的距离 - Calculate distance between my location and a MapKit pin on Swift 当我的接送位置相同时,如何计算驾驶室所覆盖的点之间的总距离? - How to calculate total distance between points covered by a Cab when my pickup and drop location are same? 通过与其他位置的距离计算位置 - Calculate location by distance from other location 如何计算两个位置的距离? - How to calculate two location distance? 计算位置与位置列表之间的距离 - calculate distance between a location and a list of locations
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM