代码之家  ›  专栏  ›  技术社区  ›  WhatTheHeckTech

标记当前位置时,坐标始终为0,0

  •  0
  • WhatTheHeckTech  · 技术社区  · 8 年前

    我正在使用谷歌地图服务制作一个使用Xcode 9.2和Swift 4的应用程序。当我按下按钮时,我希望在地图视图上用一个标记标记我的当前位置。相反,当点击按钮时,它会将我带到坐标0,0。我做错了什么?提前感谢您的帮助。

    //Location Manager
    
    var userLocation = CLLocation()
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
    userLocation = locations.last!
    
    let camera = GMSCameraPosition.camera(withLatitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude, zoom: 14);
    self.googleMapsView.camera = camera
    
    //Finally stop updating location otherwise it will come again and again in this delegate
    
    self.locationManager.stopUpdatingLocation()
    
    }
    
    //Button Marker Function
    
    @IBAction func markCurrentLocation(_ sender: UIButton) {
    
    let center = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
    
        let camera = GMSCameraPosition.camera(withLatitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude, zoom: 14);
        self.googleMapsView.camera = camera
        self.googleMapsView.isMyLocationEnabled = true
    
        let marker = GMSMarker(position: center)
    
        print("Latitude :- \(userLocation.coordinate.latitude)")
        print("Longitude :-\(userLocation.coordinate.longitude)")
    
        marker.map = self.googleMapsView
    
        marker.title = "Current Location"
    
        googleMapsView.animate(to: camera)
    
        //Finally stop updating location otherwise it will come again and again in this delegate
    
        self.locationManager.stopUpdatingLocation()
    }
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   meow2x    8 年前

    它将返回0,因为您创建了一个新的CLLocation()实例,其中没有任何内容。 从获取当前位置 locationManager(_:didUpdateLocations:) 代表

    像这样做:

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        userLocation = locations.last
    }
    

    并删除 let userLocation = CLLocation() 从您的 markCurrentLocation(_:) 方法

    还请确保在您的信息中添加请求。普利斯特 enter image description here