DanKas
DanKas

Reputation: 95

Drag GoogleMaps-Marker via swiping over map

I have a Google-Map + marker. I know how to make a marker draggable. The standard behaviour is to 'Long-Press' a marker and you can drag it. What I want is to drag the marker by swiping over the map. It shouldn't be neccessary to hit the marker. User swipes over the map from left to right and simultanously the marker changes position from left to right where the distance equals swipe-length.

I can't find a suitable solution in the GM-API. Any ideas?

I'm using Swift 2.2

var marker: GMSMarker!   

func createMarker(title: String, target: CLLocationCoordinate2D) {
    marker = GMSMarker(position: target)
    marker.appearAnimation = kGMSMarkerAnimationPop
    marker.map = map
}

func activateDragMode() {
    marker.draggable = true
    map.settings.scrollGestures = false
    map.settings.zoomGestures = false
    map.settings.rotateGestures = false
}

Upvotes: 1

Views: 2773

Answers (2)

Amrit Tiwari
Amrit Tiwari

Reputation: 990

Swift 5.1

By analysis on google api and other method, I did not get the proper one. The best and sweet answer for this question is by using pan gesture.

add the pan gesture to the mapView as

self.mapView.settings.consumesGesturesInView = false
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(self. panHandler(_:)))
self.mapView.addGestureRecognizer(panGesture)

Implementation of pan gesture method as

@objc private func panHandler(_ pan : UIPanGestureRecognizer){

        if pan.state == .ended{
            let mapSize = self.mapView.frame.size
            let point = CGPoint(x: mapSize.width/2, y: mapSize.height/2)
            let newCoordinate = self.mapView.projection.coordinate(for: point)
            print(newCoordinate)
             //do task here
        }
}

Upvotes: 0

DanKas
DanKas

Reputation: 95

The GoogleMap-API doesn't provide the method I need. But i found a solution:

map.settings.consumesGesturesInView = false
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panRecognition))
view.addGestureRecognizer(panGestureRecognizer)

func panRecognition(recognizer: UIPanGestureRecognizer) {
    if marker.draggable {
        let markerPosition = map.projection.pointForCoordinate(marker.position)
        let translation = recognizer.translationInView(view)
        recognizer.setTranslation(CGPointZero, inView: view)
        let newPosition = CGPointMake(markerPosition.x + translation.x, markerPosition.y + translation.y)
        marker.position = map.projection.coordinateForPoint(newPosition)
    }
}

I had to deactivate 'consumesGesturesInView' to add my own PanGestureRecognizer, which manipulates the marker.

Upvotes: 3

Related Questions