Reputation: 1680
I was learning GoogleMap-SDK for iOS, in the process i did searched for the above question and found satisfactory answers but not the one that's practically useful.
E.G. : Swift 3 google map add markers on touch
It adds Marker but does not have Place Name or Place Details and without that Marker is not that useful and for that i have to search other answers to get Address from the coordinates.
So , here i have combined both answers to save time of fellow developers and make it Marker more practical.
Upvotes: 1
Views: 2444
Reputation: 1680
For Swift 5.0+
First, make sure you have added
GMSMapViewDelegate
delegate to your ViewController Class
We do not need UILongPressGestureRecognizer
or UITapGestureRecognizer
for this, GMSMapViewDelegate
provides convenient default method for this.
///This default function fetches the coordinates on long-press on `GoogleMapView`
func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
//Creating Marker
let marker = GMSMarker(position: coordinate)
let decoder = CLGeocoder()
//This method is used to get location details from coordinates
decoder.reverseGeocodeLocation(CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)) { placemarks, err in
if let placeMark = placemarks?.first {
let placeName = placeMark.name ?? placeMark.subThoroughfare ?? placeMark.thoroughfare! ///Title of Marker
//Formatting for Marker Snippet/Subtitle
var address : String! = ""
if let subLocality = placeMark.subLocality ?? placeMark.name {
address.append(subLocality)
address.append(", ")
}
if let city = placeMark.locality ?? placeMark.subAdministrativeArea {
address.append(city)
address.append(", ")
}
if let state = placeMark.administrativeArea, let country = placeMark.country {
address.append(state)
address.append(", ")
address.append(country)
}
// Adding Marker Details
marker.title = placeName
marker.snippet = address
marker.appearAnimation = .pop
marker.map = mapView
}
}
}
HOPE IT HELPS !!!
Upvotes: 4