如何找出坐标之间的距离?

Joh*_*Doe 43 cllocation ios cllocationdistance swift

我想让它显示两个CLLocation坐标之间的距离.没有复杂的数学公式,有没有办法做到这一点?如果没有,你会怎么做公式?

Gle*_*wes 166

CLLocation有一个distanceFromLocation方法,因此给出了两个CLLocations:

CLLocationDistance distanceInMeters = [location1 distanceFromLocation:location2];
Run Code Online (Sandbox Code Playgroud)

或者在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
Run Code Online (Sandbox Code Playgroud)

你在这里的距离仪表所以1英里 = 1609米

if(distanceInMeters <= 1609)
 {
 // under 1 mile
 }
 else
{
 // out of 1 mile
 }
Run Code Online (Sandbox Code Playgroud)

  • 谷歌称,一米中有0.000621371英里.所以,我建议将它乘以0.000621371. (3认同)

小智 12

Swift 4.1

导入CoreLocation

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))
Run Code Online (Sandbox Code Playgroud)


Ali*_*das 7

import CoreLocation

//My location
let myLocation = CLLocation(latitude: 31.5101892, longitude: 74.3440842)

//My Next Destination
let myNextDestination = CLLocation(latitude: 33.7181584, longitude: 73.071358)

//Finding my distance to my next destination (in km)
let distance = myLocation.distance(from: myNextDestination) / 1000
Run Code Online (Sandbox Code Playgroud)


Abh*_*nav 6

试试这个:

distanceInMeters = fromLocation.distanceFromLocation(toLocation)
distanceInMiles = distanceInMeters/1609.344
Run Code Online (Sandbox Code Playgroud)

来自Apple文档:

返回值:两个位置之间的距离(以米为单位).