I want to shake the google map marker in iOS Swift

前端 未结 2 638
小鲜肉
小鲜肉 2021-01-15 16:46

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

相关标签:
2条回答
  • 2021-01-15 16:52

    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
        }
    
    0 讨论(0)
  • 2021-01-15 17:13

    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

    0 讨论(0)
提交回复
热议问题