Search code examples
iosgoogle-mapsgoogle-maps-sdk-ios

Add text to GMSMapView - write on Google Map for iOS


I want to add some text labels to GMSMapView. Of course the text should resize as the map zooms in and out. I don't see a text object in the Google Map SDK. How do I do this?


Solution

  • Here is the solution I came up with from @Saxon's suggestion, it's copied and pasted from my project so you'll have to modify to fit your needs. The idea is to render a UILabel into a UIImage, and then set the GMSGroundOverlay icon with that image. Then it resizes and all. GMSCoordinateBounds is constructed with a NorthEast and SouthWest point, so if you want to center the label at a point CenterX and CenterY you need to calculate it as below.

      UILabel *label = [UILabel new];      
      label.opaque = NO;
      label.text = @"H";
      label.font = [UIFont fontWithName: @"Arial-BoldMT" size: Normalize(32)];
      label.textColor = [UIColor blueColor];
      label.frame = CGRectMake(0, 0, Normalize(140), Normalize(140));
      label.textAlignment = NSTextAlignmentCenter;
    
      CLLocationDegrees offset = Normalize(0.03);  // change size here
      CLLocationDegrees southWestY = centerY - offset;
      CLLocationDegrees southWestX = centerX - offset;
      CLLocationDegrees northEastY = centerY + offset;
      CLLocationDegrees northEastX = centerX + offset;
    
      CLLocationCoordinate2D southWest = CLLocationCoordinate2DMake(southWestY,southWestX);
      CLLocationCoordinate2D northEast = CLLocationCoordinate2DMake(northEastY,northEastX);
      GMSCoordinateBounds *overlayBounds = [[GMSCoordinateBounds alloc] initWithCoordinate:southWest coordinate:northEast];
    
      GMSGroundOverlay *overlay = [GMSGroundOverlay groundOverlayWithBounds:overlayBounds icon:[self imageWithView:label]];
      overlay.bearing = 0;
      overlay.map = self.mapView
    
    - (UIImage *) imageWithView:(UIView *)view
    {
      UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
      [view.layer renderInContext:UIGraphicsGetCurrentContext()];
      UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
      return img;
    }