如何显示设定距离内的注释(Swift 4.0)

时间:2019-01-25 06:17:13

标签: ios swift mkmapview

我正在尝试在注释上显示1公里之内的所有公交车站,但是,UIMap显示的是不在1公里之内的注释。当我更改为10km时,它将显示距离1km以上但距离不够远的注释。

类别价值:可编码{    让busStopCode,roadName,描述:字符串    让纬度,经度:Double

enum CodingKeys: String, CodingKey {
    case busStopCode = "BusStopCode"
    case roadName = "RoadName"
    case description = "Description"
    case latitude = "Latitude"
    case longitude = "Longitude"
}

init(busStopCode: String, roadName: String, description: String, latitude: Double, longitude: Double) {
    self.busStopCode = busStopCode
    self.roadName = roadName
    self.description = description
    self.latitude = latitude
    self.longitude = longitude
}
func GetDistance(latitude: Double, longitude: Double) -> Double {
    let selectedCoordinate = CLLocation(latitude: latitude, longitude: longitude)
    let busStopCoordinate = CLLocation(latitude: Double(self.latitude), longitude: self.longitude)

    return busStopCoordinate.distance(from: selectedCoordinate)
}

ViewController类

@IBAction func GPSTrack(_ sender: Any) {
    InputAllAnnotation(busStops: stopSearchResults)
    print("Searching for nearby bus stops")
}

func InputAllAnnotation(busStops: [Value]) {
    for busStop in busStops{
        let busStopObj = BusStopAnnotation(value: busStop)
        Annotations.append(busStopObj)

        let distance = busStop.GetDistance(latitude: Double(currentLocation?.latitude ?? 0), longitude: Double(currentLocation?.longitude ?? 0))
        if  distance < 10000 {
            mapView.addAnnotation(busStopObj)
        }
    }
}

我在10公里外(但不在1公里内)标注了公共汽车站 Image of annotations on Map

1 个答案:

答案 0 :(得分:0)

检查距busStops和您(或任何值)的距离

//for 1km
let distance = myLocation.distance(from: busStopLocation) / 1000

然后检查busStop

if  distance <= 0.1{

self.displayAlert(title: "INFO", message: "BUS STOP NEAR 1KM")
}

检查公共汽车停止10公里的距离

let distance = myLocation.distance(from: busStopLocation) / 10000

如果距离> 0.1 {

self.displayAlert(title: "INFO", message: "BUS STOP AT 10KM")
}
相关问题