相机位置改变时调用函数

Call a function when camera position changes

我正在尝试在用户位置与相机位置之间的距离大于 1KM 时显示 UIButton。 我怎样才能实现这个功能?

我尝试了 func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition)func mapView(_ mapView: GMSMapView, willMove gesture: Bool),但没有得到想要的结果。

感谢您的进一步帮助!

我是这样使用的:

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

    let location: CLLocation = locations.last!
    print("Location: \(location)")

    let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude,
                                          longitude: location.coordinate.longitude,
                                          zoom: self.zoomLevel)

    if let mapView = self.mapView {

        if mapView.isHidden {
            mapView.isHidden = false
            mapView.camera = camera

        } else {
            mapView.animate(to: camera)
        }
    }
    self.calculateDistance(destiLat: Lat Coordinate, destiLongL: Long Coordinate)
}

    //This function calculates the distance between origin and destination

private func calculateDistance(destiLat: CLLocationDegrees, destiLongL: CLLocationDegrees) {

    DispatchQueue.main.async {
        let origin = CLLocation(latitude: self.locationManager.location?.coordinate.latitude ?? 0, longitude: self.locationManager.location?.coordinate.longitude ?? 0)
        let destination = CLLocation(latitude: destiLat, longitude: destiLongL)
        let distanceInMeters = origin.distance(from: destination)

        print(distanceInMeters)

        if distanceInMeters.isLessThanOrEqualTo(60) {

           //You are in range of 60 meters
           //Change the distance and show your button here
        }
    }
}

我不知道这是否是最好的方法,但它对我有用。

你可以试试

var current: CLLocation?

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

  self.current = locations.last!

}

func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {

    guard let currentLocation = current else { return } 

    let moved = CLLocation(latitude: position.target.latitude, longitude: position.target.longitude)

    if currentLocation.distance(from: moved) > 1000 {

        self.yourButton.isHidden = false
    } 
    else { //hide it }
}