如何在片段上显示用户的位置 谷歌地图斯威夫特



我有谷歌地图,想在片段中显示用户的位置(如城市(。怎么做?

这是我当前的代码:

class ViewController: UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate{
@IBOutlet weak var mapView: GMSMapView!
var latitude = -7.034323799999999
var longitude = 110.42400399999997
var locationManager = CLLocationManager()
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    mapView.delegate = self
    let camera = GMSCameraPosition.camera(withLatitude: Double(latitude), longitude: Double(longitude), zoom: 17)
    mapView.animate(to: camera)
    let markerImage = UIImage(named: "ic_home_detail_marker_location")
    let markerView = UIImageView(image: markerImage)
    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2DMake(Double(latitude), Double(longitude))
    marker.isDraggable = true
    marker.snippet = "(marker.position)"
    mapView.selectedMarker = marker
    marker.iconView = markerView
    mapView.selectedMarker = marker
    marker.map = mapView
}

}

如果要获取用户的城市或州名称,则必须使用CLGeocoder。

var currentLatitude:Double!
var currentLongitude:Double!
var cityName:String!
var stateName:String!
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print("locationManager function called")
    // Fetch current location coordinates
    let locValue:CLLocationCoordinate2D = (locationManager.location?.coordinate)!
    currentLatitude = locValue.latitude
    currentLongitude = locValue.longitude
    print("Current Location = (currentLatitude!), (currentLongitude!)")
    // Zoom to current location
    let camera: GMSCameraPosition = GMSCameraPosition.camera(withLatitude: currentLatitude!, longitude: currentLongitude!, zoom: 17.0)
    viewMap.camera = camera
    // check for current city
    CLGeocoder().reverseGeocodeLocation(locationManager.location!, completionHandler: {(placemarks, error) -> Void in
        if error != nil {
            print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
            return
        }
        if (placemarks?.count)! > 0 {
            let pm = placemarks?[0]
            self.cityName = (pm?.locality)!
            self.stateName = (pm?.administrativeArea)
            print("Current City: (self.cityName!)")
            print("Curret State: (self.stateName!)")
        }
        else {
            print("Problem with the data received from geocoder")
        }
    })
    locationManager.stopUpdatingLocation()
}

现在,您将当前城市存储在变量中。

下一步是当用户触摸标记时,它应该显示城市名称。为此,实现这一点:

必须添加此委托:

GMSMapViewDelegate

这是标记功能,当用户点击它时。

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    mapView.delegate = self
    marker.snippet = ("Current city: (cityName!)")
    // return false so as to show the marker details or
    //   return true to hide marker details.
    return false
}

最新更新