How do I add a text label on a polygon in Google Maps in iOS ? I tried to add an overlay but it will only accept images not text? I am using google maps for ios with Swift on iOS 9.
This is the portion of code troubling me :
func updateUIMap(){
var str = "Hello"
var data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
var drawText = NSString(data: data!, encoding: NSUTF8StringEncoding)
let size = CGSize(width: 24.0,height: 24.0)
var inImage = UIImage()
var textColor: UIColor = UIColor.blackColor()
var textFont: UIFont = UIFont(name: "Helvetica Bold", size: 12)!
UIGraphicsBeginImageContext(size)
let textFontAttributes = [
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor,
]
inImage.drawInRect(CGRectMake(0, 0, size.width, size.height))
var rect: CGRect = CGRectMake(24, 24, size.width, size.height)
drawText.drawInRect(rect, withAttributes: textFontAttributes)
var newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
var overlay = GMSGroundOverlay(position: myposition, icon: newImage, zoomLevel:20)
overlay.bearing = 0
overlay.map = self.mapView
}
I've found personally that the easiest way to do this is by adding a
GMSMarker
with aUILabel
as it'siconView
property.This approach can run into performance issues if you're adding a TON of markers to the map, but it's very effective if you need to add some labels to a map.
Your
UIGraphics
drawing method might not be correct, you can try the following code to make a new image from a text: