google maps iOS SDK: custom icons to be used as markers

Here is what I have done

let marker = GMSMarker()

// I have taken a pin image which is a custom image
let markerImage = UIImage(named: "mapMarker")!.withRenderingMode(.alwaysTemplate)

//creating a marker view
let markerView = UIImageView(image: markerImage)

//changing the tint color of the image
markerView.tintColor = UIColor.red

marker.position = CLLocationCoordinate2D(latitude: 28.7041, longitude: 77.1025)

marker.iconView = markerView
marker.title = "New Delhi"
marker.snippet = "India"
marker.map = mapView

//comment this line if you don't wish to put a callout bubble
mapView.selectedMarker = marker

The output is

enter image description here

And my marker image was

enter image description here

You can change your color as per your need. Also if you want something in rectange, you can just create a simple small rectangular image and use it like I did above and change the color of your need.

Or if you want a rectangle with text within it, you can just create a small UIView with some label and then convert that UIView in UIImage and can do the same thing.

//function to convert the given UIView into a UIImage
func imageWithView(view:UIView) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
    view.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}

Hope it helps!!

Leave a Comment