I have been looking at the google documentation to get the current location, but i am struggling to specify the location in the ViewDidLoad, as you can see i have set the Location fixed to Syndey Australia. In the google doc documentation when specifying the current location, they are using the "default location.coordinate" , i cannot access defaultLocation.coordinate in my code .
here is a link to the documenation : https://developers.google.com/maps/documentation/ios-sdk/current-place-tutorial
this is the code inside the viewDidLoad
GMSServices.provideAPIKey("AIzaSyARsPfNs54hrUAC4yKtHeu2jXfGjeA0b-E")
GMSPlacesClient.provideAPIKey("AIzaSyARsPfNs54hrUAC4yKtHeu2jXfGjeA0b-E ")
let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
view = mapView
// creating the marker //
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = mapView
This is my extenstion code
extension MapsViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location : CLLocation = locations.last!
print("Location:\(location)")
let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude, longitude: location.coordinate.longitude, zoom: zoomLevel)
if mapView.isHidden {
mapView.isHidden = false
mapView.camera = camera
}
else {
mapView.animate(to: camera)
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .restricted:
// display the map the default location
mapView.isHidden = false
case .denied :
print("User denied access to location")
mapView.isHidden = false
case .notDetermined :
print("Location status not deteremined")
case .authorizedAlways : fallthrough
case . authorizedWhenInUse :
print("Location status is OK")
}
}
You have added wrong code in your method searchLocationPressed, Please update it as follow.
#IBAction func searchLocationPressed(_ sender: UIBarButtonItem) {
let autocomplete = GMSAutocompleteViewController()
autocomplete.delegate = self
self.present(autocomplete, animated: true, completion: nil)
}
Your mistake is you are presenting UISearchController instead of GMSAutocompleteViewController.
Related
This is how I init the map - GMSMapView
class ViewController: UIViewController {
var map = GMSMapView()
override func viewDidLoad() {
super.viewDidLoad()
setupGoogleView()
}
private func setupGoogleView() {
guard let coordinates = getUserLocation() else { return }
let camera = GMSCameraPosition.camera(withLatitude: coordinates.latitude, longitude: coordinates.longitude, zoom: 16.0)
self.map = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
map.settings.tiltGestures = false
map.mapType = .satellite
map.delegate = self
map.frame = view.frame
self.view.addSubview(map)
}
}
The problem comes when I call this function from somewhere else in the file
private func animateTo(location: CLLocationCoordinate2D) {
DispatchQueue.main.async {
let cameraPosition = GMSCameraPosition(target: location, zoom: 20)
self.map.animate(toLocation: location)
self.map.animate(to: cameraPosition)
}
}
I am trying to relocate the camera to some coordinates, but nothing happens.
I have tried every solution on stackoverflow and google.
I have lat and lng in the location - checked. The function is called - checked.
I have also tried to self.view.layoutSubviews(), self.view.layoutIfNeeded(), and also for map
try to use CLLocationManagerDelegate
// Handle authorization for the location manager.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .restricted:
print("Location access was restricted.")
case .denied:
print("User denied access to location.")
// Display the map using the default location.
mapView.isHidden = false
case .notDetermined:
print("Location status not determined.")
case .authorizedAlways: fallthrough
case .authorizedWhenInUse:
print("Location status is OK.")
getFilialList()
#unknown default:
fatalError()
}
}
then
// Handle incoming location events.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location: CLLocation = locations.last!
print("Location: \(location)")
let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude,
longitude: location.coordinate.longitude,
zoom: 12)
DispatchQueue.main.async {
self.mapView.animate(to: camera)
self.locationManager.stopUpdatingLocation()
}
}
I manage to solve the issue with this:
self.view.subviews.forEach { (view) in
if let mapView = view as? GMSMapView {
// do update on mapView here
}
}
I have been looking at the google documentation to get the current location, but i am struggling to specify the location in the ViewDidLoad, as you can see i have set the Location fixed to Syndey Australia. In the google doc documentation when specifying the current location, they are using the "default location.coordinate" , i cannot access defaultLocation.coordinate in my code .
here is a link to the documenation : https://developers.google.com/maps/documentation/ios-sdk/current-place-tutorial
this is the code inside the viewDidLoad
GMSServices.provideAPIKey("AIzaSyARsPfNs54hrUAC4yKtHeu2jXfGjeA0b-E")
GMSPlacesClient.provideAPIKey("AIzaSyARsPfNs54hrUAC4yKtHeu2jXfGjeA0b-E ")
let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
view = mapView
// creating the marker //
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = mapView
This is my extenstion code
extension MapsViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location : CLLocation = locations.last!
print("Location:\(location)")
let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude, longitude: location.coordinate.longitude, zoom: zoomLevel)
if mapView.isHidden {
mapView.isHidden = false
mapView.camera = camera
}
else {
mapView.animate(to: camera)
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .restricted:
// display the map the default location
mapView.isHidden = false
case .denied :
print("User denied access to location")
mapView.isHidden = false
case .notDetermined :
print("Location status not deteremined")
case .authorizedAlways : fallthrough
case . authorizedWhenInUse :
print("Location status is OK")
}
}
I think you missed to add key NSLocationWhenInUseUsageDescription in your Info.plist file.
Add this key to the usage description.
It should then show an iOS system pop-up to allow location access.
I have read your question and checked you given link for Map Tutorial. I found some code missing in your viewDidLoad method:
locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.distanceFilter = 50
locationManager.startUpdatingLocation()
locationManager.delegate = self
placesClient = GMSPlacesClient.shared()
Without assign delegate to the object of CLLocationManager like locationManager.delegate = self
I don't think even your extension would be called (CLLocationManagerDelegate).
Also
As per #Let's_Create answer info.plist shold have following keys to explain the user how the app uses this.
dataNSLocationAlwaysAndWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription
I am using Google Maps service for an app I am making using Xcode 9.2 and Swift 4. When I press a button I would like my current location to be marked on the map view with a marker above it. Instead, when tapping the button it takes me to the coordinates 0,0. What am I doing wrong? Thank you for all your help in advance.
//Location Manager
var userLocation = CLLocation()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
userLocation = locations.last!
let camera = GMSCameraPosition.camera(withLatitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude, zoom: 14);
self.googleMapsView.camera = camera
//Finally stop updating location otherwise it will come again and again in this delegate
self.locationManager.stopUpdatingLocation()
}
//Button Marker Function
#IBAction func markCurrentLocation(_ sender: UIButton) {
let center = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
let camera = GMSCameraPosition.camera(withLatitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude, zoom: 14);
self.googleMapsView.camera = camera
self.googleMapsView.isMyLocationEnabled = true
let marker = GMSMarker(position: center)
print("Latitude :- \(userLocation.coordinate.latitude)")
print("Longitude :-\(userLocation.coordinate.longitude)")
marker.map = self.googleMapsView
marker.title = "Current Location"
googleMapsView.animate(to: camera)
//Finally stop updating location otherwise it will come again and again in this delegate
self.locationManager.stopUpdatingLocation()
}
It will return 0 because you created a new CLLocation() instance with nothing in it.
Get the current location from the locationManager(_:didUpdateLocations:) delegate.
Do it like:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
userLocation = locations.last
}
And remove let userLocation = CLLocation() from your markCurrentLocation(_:) method
Also be sure to add request in your info.plist
I am using Google Map on iOS, and I am getting the marker at my location but not getting camera position to my location. I have seen lots of tutorials but not getting any solution.
My code is :
mapView = GMSMapView()
locationManager = CLLocationManager()
// locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
placesClient = GMSPlacesClient.shared()
// GOOGLE MAPS SDK: COMPASS
mapView.settings.compassButton = true
// GOOGLE MAPS SDK: USER'S LOCATION
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
mapView.animate(toBearing: 0)
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
if let location = locations.last
{
print("location\(String(describing: location))")
// mapView.clear()
let marker = GMSMarker(position: CLLocationCoordinate2D(latitude:location.coordinate.latitude, longitude: location.coordinate.longitude))
marker.map = mapview
mapView.camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude,
longitude: location.coordinate.longitude,
zoom: 50)
}
locationManager.stopUpdatingLocation()
}
Be sure to check GMSMapView.padding. It can differ from the rect of your GMSMapView, then camera will point to another position.
i'm a beginner in developing an i'm adding a google map on a view of my application, following a tutorial i used this code
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location: CLLocation = locations.last!
print("Location: \(location)")
let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude,
longitude: location.coordinate.longitude,
zoom: zoomlevel)
let marker = GMSMarker()
marker.title = "My Position"
marker.map = mapView
if mapView.isHidden {
mapView.isHidden = false
mapView.camera = camera
} else {
mapView.animate(to: camera)
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .restricted:
print("Location access was restricted.")
case .denied:
print("User denied access to location.")
mapView.isHidden = false
case .notDetermined:
print("Location status not determined.")
case .authorizedAlways: fallthrough
case .authorizedWhenInUse:
print("Location status is OK.")
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
locationManager.stopUpdatingLocation()
print("Error: \(error)")
}
to find the user location, now i would like to see on the map the places (google places) that are on a X distance from the user position, how can i do it? i searched on the google places doc but not find a valid answer
Add another marker onTap on mapView and make it draggable and use CLLocationDistance to measure distance between 2 locations.
let distanceInMeters = self.locationManager.location?.distance(from: newMarkerLocation!)