CSStudent
CSStudent

Reputation: 425

How to label map markers in Google maps ios

I have a few markers on the map and they each represent a path with a different theme. I want the user to be able to see each of the themes before selecting a marker so I was planning on adding a simple text label above each of them. This doesn't seem to be an embedded function in google maps for ios. Is there any way around this?

Upvotes: 5

Views: 7525

Answers (2)

alana314
alana314

Reputation: 633

I'm a beginner to swift, but I was able to convert Daij-Djan's answer:

let label = UILabel()
label.frame = CGRect(x:0, y:0, width: 50, height: 20)
label.text = "test"
label.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.5)
label.textColor = UIColor.whiteColor()
label.adjustsFontSizeToFitWidth = true
UIGraphicsBeginImageContextWithOptions(label.frame.size, false, UIScreen.mainScreen().scale)
if let currentContext = UIGraphicsGetCurrentContext()
{
    label.layer.renderInContext(currentContext)
    let imageMarker = UIImage()
    imageMarker = UIGraphicsGetImageFromCurrentImageContext()
    let marker = GMSMarker(position: CLLocationCoordinate2DMake(lat, long))
    marker.icon = imageMarker
    marker.map = mapView
}
UIGraphicsEndImageContext()

Upvotes: 2

Daij-Djan
Daij-Djan

Reputation: 50089

Set up a UILabel, set it up, render it to a UIImage and set that as the marker's icon.

//setup label
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
label.text = @"test";
label.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.5];

//grab it
UIGraphicsBeginImageContextWithOptions(label.bounds.size, NO, [[UIScreen mainScreen] scale]);
[label.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * icon = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//prepare options
GMSMarkerOptions *options = [GMSMarkerOptions options];
options.position = CLLocationCoordinate2DMake(latitude, longitude);
options.title = [NSString stringWithFormat:@"#%d", count_];
options.icon = icon;

Upvotes: 23

Related Questions