获取谷歌地图的纬度和经度中心

7

我想要展示全屏地图视图,始终获取地图视图中心的纬度和经度,并在此点显示标记。

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

    let lat = mapView.camera.target.latitude
    print(lat)

    let lon = mapView.camera.target.longitude
    print(lon)


    marker.position = CLLocationCoordinate2DMake(CLLocationDegrees(centerPoint.x) , CLLocationDegrees(centerPoint.y))
    marker.map = self.mapView
    returnPostionOfMapView(mapView: mapView)

  }

  func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
    print("idleAt")

    //called when the map is idle

    returnPostionOfMapView(mapView: mapView)

  }

  func returnPostionOfMapView(mapView:GMSMapView){
    let geocoder = GMSGeocoder()
    let latitute = mapView.camera.target.latitude
    let longitude = mapView.camera.target.longitude




    let position = CLLocationCoordinate2DMake(latitute, longitude)
    geocoder.reverseGeocodeCoordinate(position) { response , error in
      if error != nil {
        print("GMSReverseGeocode Error: \(String(describing: error?.localizedDescription))")
      }else {
        let result = response?.results()?.first
        let address = result?.lines?.reduce("") { $0 == "" ? $1 : $0 + ", " + $1 }

        print(address)
//        self.searchBar.text = address
      }
    }
  }

我在这个代码中使用了,如何知道在returnPostionOfMapView方法中返回的纬度和经度是地图视图的中心位置,并在此位置显示标记?
1个回答

22

您正在正确地使用谷歌地图的func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition)代理来获取地图中心。

为中心坐标取一个变量。

var centerMapCoordinate:CLLocationCoordinate2D!

实现此委托以获取中心位置。

func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
    let latitude = mapView.camera.target.latitude
    let longitude = mapView.camera.target.longitude
    centerMapCoordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    self.placeMarkerOnCenter(centerMapCoordinate:centerMapCoordinate)
}

在中心点放置标记的函数

func placeMarkerOnCenter(centerMapCoordinate:CLLocationCoordinate2D) {
    let marker = GMSMarker()
    marker.position = centerMapCoordinate
    marker.map = self.mapView
}
在这种情况下,您将获得许多标记。因此,请全局保持标记并检查它是否已经存在,只需更改位置。
var marker:GMSMarker!

func placeMarkerOnCenter(centerMapCoordinate:CLLocationCoordinate2D) {
    if marker == nil {
        marker = GMSMarker()
    }
    marker.position = centerMapCoordinate
    marker.map = self.mapView
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接