How to show recenter button only when map moves using Swift? - ios

I'm using the default Google Map recenter button which is shown by default. How do I ensure that the recenter button is not shown by default and it's only shown when someone moves the map using Swift?
func SetupMap() {
googleMapView.settings.myLocationButton = true
}

That's pretty easy. You know how to toggle the visibility of the myLocationButton, so what's left is to think harder.
If you take time to review the GoogleMap's GMSMapViewDelegate, you will see that there are couple of methods/functions that will allow you to further your idea.
So set your mapView's delegate to your class (controller), and conform to that GMSMapViewDelegate protocol, and then implement those methods.
willMove
didChange position
These are all you need.
The willMove gets invoked when you start dragging the mapView. On the other hand, the didChange position gets called when the camera did change.
If you do these things, you'll get even nearer towards your goal. However, you might need some debounce feature in your code, because you only want to hide the location button just once, just after the user stops dragging the camera.
var debounce_timer: Timer?
extension MapsViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, willMove gesture: Bool) {
print("GMS: will move")
mapView.settings.myLocationButton = true
}
func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
print("GMS: didChane camera position")
debounce_timer?.invalidate()
debounce_timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { _ in
mapView.settings.myLocationButton = false
}
}
}
Voila!
Demo:

Related

Get lat/long from the google mapview

I need to get the lat/long of the location where user taps on the google map view. Is there a necessity to open GooglePlacePickerViewController for this? I need to achieve this in the GMSMapView which is used to show user current location.
It is simple use Delegate method
First set delegate
self.mapView.delegate = self
Then just
extension YourViewController:GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
// USER TAP ON coordinate
}
}
Suggestion : Just go through this tutorial https://medium.freecodecamp.org/how-you-can-use-the-google-maps-sdk-with-ios-using-swift-4-a9bba26d9c4d will not take more than 20 min that my promise will conver all the basic stuff. :)
If you need points of view based system. for example if you want what is exact point where user tap according to view X, Y
Then
you can do it like this
let points:CGPoint = mapView.projection.point(for:coordinates)
Bingo !!
assign delegate like this.
mapView.delegate = self
And use GMSMapViewDelegate to use below method
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
print("You tapped at Location \(coordinate.latitude), \(coordinate.longitude)")
}

Can't select MKViewAnnotation twice?

I've got pins placed on a map and when I tap on them I'm calling the didSelect. The function only gets called the first time the pin is tapped, and after that it's not called on that same pin again unless I select another pin and then come back and tap it.
What that sounds like to me is the pin is being selected, and didSelect can only be called in unselected pins, so when I go tap on another pin it's deselecting the first pin and making it tappable again.
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
view.isSelected = false
}
I don't understand why the above code does not work.
How can I allow my annotations be tapped more than one time in a row?
Try with this method deselectAnnotation
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
//do what you need here
mapView.deselectAnnotation(view.annotation, animated: true)
}
Hope this helps
There is another option, and that is to add a Gesture Recognizer for on the annotationView.
This will enable showing the callout view (since de-selecting the annotation immediately will not show it).
internal func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(mapPinTapGestureRecognizer)))
}
#objc private func mapPinTapGestureRecognizer(gestureRecognizer: UITapGestureRecognizer) {
// Will get called on the second time the pin is selected.
// And then, after that, it will be called every time.
}
Just don't forget to remove the recognizer when the annotation is no longer selected.
internal func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
// Remove the gesture recognizer when the annotation is no longer selected.
}

Tap gesture for MapKit

Currently I have a map that has several Annotations.
For the Annotations I have
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView){
// Do your annotation click work
}
Is it possible to do this for tapping the Map only and not the Annotation and how can I do it?
In ViewWillAppear method :
let gestureRecognizer = UITapGestureRecognizer(target: self, action:"triggerTouchAction:")
mapView.addGestureRecognizer(gestureRecognizer)
And Whatever information you want to show just add code in following method :
func triggerTouchAction(gestureReconizer: UITapGestureRecognizer) {
//Add alert to show it works
}
Hope it going to help you to resolve issue.

Fixed marker on google maps for ios

I am using google maps SDK for ios. I want to make a marker fixed in the center of the screen, so when user drags the map, the marker does not move and stays in the center. I am also trying to read the coordinate of the center after the drag. Any input would be appreciated. Thanks!
I would rather display view on top of GMSMapView (do not use markers for that). Since you have screen position for map view, that should be easy to place your view in correct position.
To get coordinates you can use mapView.projection.coordinateForPoint
Documentation is here
To know that drag is finished, make you view controller (or any other object) delegate of map view (GMSMapViewDelegate) and implement mapView:idleAtCameraPosition: method.
Docs are here
Create outlet of GMSMapView and attached Image at the center of the map and search bar at the top to present the location name.
Drag the map on Device, which will trigger 2 delegate method of GMSMapViewDelegate.
func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) 
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) 
/**
* Called repeatedly during any animations or gestures on the map (or once, if the camera is
* explicitly set). This may not be called for all intermediate camera positions. It is always
* called for the final position of an animation or gesture.
*/
func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
print("didchange")> >
returnPostionOfMapView(mapView: mapView)
}
/**
* Called when the map becomes idle, after any outstanding gestures or animations have completed (or
* after the camera has been explicitly set).
*/
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
print("idleAt")
//called when the map is idle
returnPostionOfMapView(mapView: mapView)
}
//Convert the location position to address
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 }
self.searchBar.text = address
}
}
}
Github Demo Project

need mapView not to updateLocation

I have got mapView, and its delegate method
func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) {
mapView.userTrackingMode = MKUserTrackingMode.None
var eye = CLLocationCoordinate2DMake(userLocation.coordinate.latitude, userLocation.coordinate.longitude)
var cam = MKMapCamera(lookingAtCenterCoordinate: eye, fromEyeCoordinate: eye, eyeAltitude: 10000)
UIView.animateWithDuration(1, animations: { () -> Void in
mapView.camera = cam
})
}
and it works some random way. it executes when view loads, and than when I am scrolling map to another country or city and zoom, it can(sometimes, now always) return me to my current location. It is curious cause my current location didnt changes and the delegate shouldnt execute.
I need do somehow this thing DONT HAPPENED. So i want to make my map zoom to current location only when location changed, in other way I need to have free map for scrolling.
You have to set you controller as CLLocationManagerDelegate, then declare a variable like:
var locationManager:CLLocationManager = CLLocationManager()
then in your viewDidLoad method:
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.stopUpdatingLocation()
It should prevent to call func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!).
Pay attention that you have to re-enbale it in case you need to update map center with your coordinate without manual scrolling to you actual position.

Resources