I want to shake the google map marker in iOS Swift

别等时光非礼了梦想. 提交于 2019-12-19 10:12:48

问题


I am working on a project where I wants to shake the marker on google Map. I am using the custom marker icon to represent on the map. Like a head of person is shaking. I don't know how to do it and search a lot but didn't find any solution.


回答1:


You can add a CAKeyframeAnimation or CABasicAnimation to your marker.iconView!.layer we add a UIView with a frame bigger than our UIImageView inside then we need to adjust the anchor point of your UIImageView to bottom in vertical and horizontally centered this will be the point that will work as pivot in our animation, our animation will be a rotation animation in Z plane from -30 to 30 grades to achieve the animation desired.This is the simplest way to do this but you can also define a custom class and make a lot of other things

    let marker = GMSMarker(position: CLLocationCoordinate2D(latitude: 22.404963, longitude: -79.961755))

    //we need a bigger UIView to avoid the clip problem with the UIImageView
    marker.iconView = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 40))
    let imageView = UIImageView(frame: CGRect(x: (marker.iconView?.frame.width)!/2 - 14, y: (marker.iconView?.frame.height)! - 36, width: 28, height: 36))
    imageView.contentMode = .scaleAspectFit
    imageView.image = UIImage(named: "iconomapa")
    marker.iconView?.addSubview(imageView)
    imageView.layer.anchorPoint = CGPoint(x: 0.5, y: 1.0) //we need adjust anchor point to achieve the desired behavior
    imageView.layer.frame = CGRect(x: (marker.iconView?.frame.width)!/2 - 14, y: (marker.iconView?.frame.height)! - 36, width: 28, height: 36) //we need adjust the layer frame

    let animation = CAKeyframeAnimation()
    animation.keyPath = "transform.rotation.z"
    animation.values = [ 0, -30 * .pi / 180.0, 30 * .pi / 180.0 , 0]
    animation.keyTimes = [0, 0.33 , 0.66 , 1]
    animation.duration = 1;
    animation.isAdditive = false;
    animation.isRemovedOnCompletion = true
    animation.repeatCount = .infinity

    marker.iconView!.subviews[0].layer.add(animation, forKey: "shakeAnimation")
    marker.map = self.mapView

here is how it looks

Hope this helps




回答2:


You can use marker property to rotate your marker ,

marker.rotation =  (you_angle_in_degree) * M_PI / 180.0f; 
 //  convert  degree to radian 

The Horizontally Shake animation you can get after some time interval change the degree for of the rotation , you can use timer ,

  // create a timer
  timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)

 func timerAction() {
       // Place you aniamtion logic here , 
       // every 0.5 second change the rotation of your maker
    }


来源:https://stackoverflow.com/questions/45137032/i-want-to-shake-the-google-map-marker-in-ios-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!