简体   繁体   中英

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?

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;

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM