web-dev-qa-db-ja.com

座標間の距離を調べる方法は?

2つのCLLocation座標間の距離を表示するようにします。複雑な数式なしでこれを行う方法はありますか?数式を使ってどうしますか?

41
John Doe

CLLocationにはdistanceFromLocationメソッドがあるため、2つのCLLocationが与えられます。

CLLocationDistance distanceInMeters = [location1 distanceFromLocation:location2];

またはSwift 4:

//: Playground - noun: a place where people can play

import CoreLocation


let coordinate₀ = CLLocation(latitude: 5.0, longitude: 5.0)
let coordinate₁ = CLLocation(latitude: 5.0, longitude: 3.0)

let distanceInMeters = coordinate₀.distance(from: coordinate₁) // result is in meters

ここに到着します距離 in メーター so 1マイル = 1609メーター

if(distanceInMeters <= 1609)
 {
 // under 1 mile
 }
 else
{
 // out of 1 mile
 }
162
Glenn Howes

Swift 4.1

import CoreLocation

//My location
let myLocation = CLLocation(latitude: 59.244696, longitude: 17.813868)

//My buddy's location
let myBuddysLocation = CLLocation(latitude: 59.326354, longitude: 18.072310)

//Measuring my distance to my buddy's (in km)
let distance = myLocation.distance(from: myBuddysLocation) / 1000

//Display the result in km
print(String(format: "The distance to my buddy is %.01fkm", distance))
10

これを試してください:

distanceInMeters = fromLocation.distanceFromLocation(toLocation)
distanceInMiles = distanceInMeters/1609.344

Appleドキュメント から:

戻り値:2つの場所間の距離(メートル単位)。

6
Abhinav

Objective-Cの場合

distanceFromLocationを使用して、2つの座標間の距離を見つけることができます。

コードスニペット:

CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:lat1 longitude:lng1];

CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:lat2 longitude:lng2];

CLLocationDistance distance = [loc1 distanceFromLocation:loc2];

出力はメートル単位で送られます。

1
Vijay
func calculateDistanceInMiles(){

    let coordinate₀ = CLLocation(latitude:34.54545, longitude:56.64646)
    let coordinate₁ = CLLocation(latitude: 28.4646, longitude:76.65464)
    let distanceInMeters = coordinate₀.distance(from: coordinate₁)
    if(distanceInMeters <= 1609)
    {
        let s =   String(format: "%.2f", distanceInMeters)
        self.fantasyDistanceLabel.text = s + " Miles"
    }
    else
    {
        let s =   String(format: "%.2f", distanceInMeters)
        self.fantasyDistanceLabel.text = s + " Miles"

    }
}
1
Saurabh Sharma

Swift 4の場合

   let locationOne = CLLocation(latitude: lat, longitude: long)
   let locationTwo = CLLocation(latitude: lat,longitude: long)

  let distance = locationOne.distance(from: locationTwo) * 0.000621371

  distanceLabel.text = "\(Int(round(distance))) mi"
1
Faris