Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift | Show image in Custom GMSMarker

custom Marker with user profile pics

I want to show user's profile picture in my custom marker for google maps. Like all others, I have tried this code in init: of customMarker

self.location = location
position = location
icon = UIImage(named: "live location")
groundAnchor = CGPoint(x: 0.5, y: 1)

Is there any possible way to show another image in the circle of the marker icon. ex. using xib.

like image 524
Sarath Kumar Avatar asked Dec 02 '25 15:12

Sarath Kumar


1 Answers

You can use given two methods:

func drawImageWithProfilePic(pp: UIImage, image: UIImage) -> UIImage {

    let imgView = UIImageView(image: image)
    let picImgView = UIImageView(image: pp)
    picImgView.frame = CGRect(x: 0, y: 0, width: 30, height: 30)

    imgView.addSubview(picImgView)
    picImgView.center.x = imgView.center.x
    picImgView.center.y = imgView.center.y - 7
    picImgView.layer.cornerRadius = picImgView.frame.width/2
    picImgView.clipsToBounds = true
    imgView.setNeedsLayout()
    picImgView.setNeedsLayout()

    let newImage = imageWithView(view: imgView)
    return newImage
}

func imageWithView(view: UIView) -> UIImage {
    var image: UIImage?
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
    if let context = UIGraphicsGetCurrentContext() {
        view.layer.render(in: context)
        image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    }
    return image ?? UIImage()
}

Here pp is your profile pic and image is the pic icon. You can set the frame of Profile pic according to you. I have tried this:

Edit

let marker = GMSMarker(position: coordinate)
marker.icon = drawImageWithProfilePic(pp: imgPP, image: img)
marker.appearAnimation = GMSMarkerAnimation.pop
marker.map = viewGoogleMap

and here is the output:

enter image description here

like image 170
Chanchal Chauhan Avatar answered Dec 05 '25 03:12

Chanchal Chauhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!