【问题标题】:Get Latitude and longitude center of Google Map获取谷歌地图的经纬度中心
【发布时间】:2017-06-24 13:04:08
【问题描述】:

我想全屏显示mapView,总是获取mapView中心的经纬度,并在这个点显示标记。

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 方法中返回的纬度和经度是中心 mapView 的位置并在该位置显示标记?

【问题讨论】:

    标签: ios swift google-maps


    【解决方案1】:

    您使用谷歌地图的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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-23
      相关资源
      最近更新 更多