Search code examples
iosgoogle-mapsgoogle-maps-api-3gmsmapview

GMSMarker iOS issue


I use this code to create marker on Google Map for iOS.

self.mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
    self.mapView.myLocationEnabled = YES;
    self.mapView.accessibilityElementsHidden = NO;
    self.mapView.frame = self.view.bounds;
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.mapView.delegate = self;
    self.mapView.settings.myLocationButton = YES;
    [self.view addSubview:self.mapView];

GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(-33.86, 151.20);
marker.map = self.mapView;

But I need the marker to look like this:

enter image description here

I know how to do that with Apple Map, but I need to use Google Map (because in some cities Apple Map doesn't show almost anything).

For google map I found only code like this:

marker.icon = image; // image from xib file

So I will need to create image from xib for each marker. I will have a lot of markers, so may be with this approach I will get memory warning.

Do anybody know better way to implement marker like that?


Solution

  • Since GMSMarker only allows an UIImage to be set as icon, I implemented something similar like this: (it's in Swift, but the concept is the same for Objective C)

    var gasView = UIView(frame:CGRectMake(0, 0, 30, 37))
    //Add Label
    var lblPrecio = UILabel(frame: CGRectMake(0, 37-18, 30, 10))
    lblPrecio.text = "hello"
    lblPrecio.textAlignment = NSTextAlignment.Center
    gasView.addSubview(lblPrecio)
    //Add Logo
    var logo = UIImageView(frame: CGRectMake(30-23, 2, 16, 16))
    logo.image = UIImage(named: "Logo")
    gasView.addSubview(logo)
    //Add Callout Background Image
    gasView.backgroundColor = UIColor(patternImage: UIImage(named: "Callout")!)
    
    marker.icon = imageFromView(gasView)
    

    Where the function imageFromView is the following:

    private func imageFromView(aView:UIView) -> UIImage {
        if(UIScreen.mainScreen().respondsToSelector("scale")) {
            UIGraphicsBeginImageContextWithOptions(aView.frame.size, false, UIScreen.mainScreen().scale)
        }
        else {
            UIGraphicsBeginImageContext(aView.frame.size)
        }
        aView.layer.renderInContext(UIGraphicsGetCurrentContext())
        var image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    

    Hope this helps.