【问题标题】:Call a function when camera position changes当相机位置改变时调用函数
【发布时间】:2020-01-27 11:35:51
【问题描述】:

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

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

感谢您的进一步帮助!

【问题讨论】:

    标签: ios swift google-maps swift4


    【解决方案1】:

    你可以试试

    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 }
    }
    

    【讨论】:

    • 感谢为我工作,如果我只想在缩放级别更改时显示按钮,我该怎么做?
    【解决方案2】:

    我是这样使用它的:

        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
            }
        }
    }
    

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

    【讨论】:

    • 感谢您的回复,您的代码也运行良好;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    相关资源
    最近更新 更多