6

I'm trying to use the fitBounds method to fit all my markers in the google maps camera view. So I have my markers stored in markersArray and I use the following code to init GMSCoordinateBounds with the 1st and 2nd markers in markersArray which works fine.

Then when I try to add the 3rd marker from markersArray using includingCoordinate I don't see the bounds updating anything neither in its values nor in the map is it changing the camera accordingly.

The weird thing is that in Google maps SDK for iOS docs it's saying that GMSCoordinateBounds "is immutable and can't be modified after construction." Does that make sense? I can't change the bounds after constructing them? Then how do I add more coordinates to the bounds?

Here is my code:

    GMSCoordinateBounds *bounds= [[GMSCoordinateBounds alloc] init];

    GMSMarker *marker1 = [markersArray objectAtIndex:0];
    GMSMarker *marker2 = [markersArray objectAtIndex:1];
    GMSMarker *marker3 = [markersArray objectAtIndex:2];

    bounds = [[GMSCoordinateBounds alloc] initWithCoordinate:marker1.position    coordinate:marker2.position];

    //Add the 3rd marker to the bounds
    [bounds includingCoordinate:marker3.position];

    GMSCameraUpdate *update = [GMSCameraUpdate fitBounds:bounds withPadding:600.0f];
    [mapView_ animateWithCameraUpdate:update];
Ali
  • 4,205
  • 4
  • 25
  • 40

1 Answers1

41

The GMSCoordinateBounds includingCoordinate: method returns a new bounds containing the combination of the original bounds and the new location, it doesn't modify the object you call it on.

So you would need something like this:

bounds = [bounds includingCoordinate: marker3.position];
Saxon Druce
  • 17,406
  • 5
  • 50
  • 71
  • Thanks it works fine now. It is so obvious I feel embarrassed for asking. – Ali Jun 13 '13 at 09:11
  • 1
    How's that google didn't include a method that receives an array of locations and return you the bounds that fit all them? The way is implemented now forces you to initialize it with two locations only, and then loop thro the rest calling includingCoordinate. Am I missing a better way to do it? – Pauls Dec 18 '14 at 23:56
  • You are a saver, I didn't notice the returned value, thnx – Boda Oct 04 '15 at 13:34
  • same to me here haha very nice – Gustavo Baiocchi Costa Apr 26 '17 at 14:59