I want to show full screen mapView, always get Latitude and longitude of center of mapView and show marker in this point.
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
}
}
}
i use this code in how can know Latitude and longitude that return in returnPostionOfMapView method is position of center mapView and show marker in this position?
Go to the Google Cloud Console. Click the Select a project button, then select the same project you set up for the Maps JavaScript API and click Open. From the list of APIs on the Dashboard, look for Geocoding API. If you see the API in the list, you're all set.
You are doing it right to get the center of the map by using the google maps's func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition)
delegate.
Take a variable for center coordinates
var centerMapCoordinate:CLLocationCoordinate2D!
Implement this delegate to know the center position.
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)
}
Function to place a marker on center point
func placeMarkerOnCenter(centerMapCoordinate:CLLocationCoordinate2D) {
let marker = GMSMarker()
marker.position = centerMapCoordinate
marker.map = self.mapView
}
In this case you will get a lot of markers. So keep a global hold of marker and check if it is already present, just change the position
var marker:GMSMarker!
func placeMarkerOnCenter(centerMapCoordinate:CLLocationCoordinate2D) {
if marker == nil {
marker = GMSMarker()
}
marker.position = centerMapCoordinate
marker.map = self.mapView
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With