Подтвердить что ты не робот

IOS, Как использовать GMSCoordinateBounds, чтобы показать все маркеры карты?

Я хочу показать все маркеры, которые есть на моей карте, после некоторых поисков я обнаружил, что это должно быть сделано с помощью GMSCoordinateBounds (Google Maps SDK). Я прочитал официальную документацию по этому поводу, но я не понимаю, как ее использовать. и реализовать это в моем коде.

https://developers.google.com/maps/documentation/ios/reference/interface_g_m_s_camera_update#aa5b05606808272f9054c54af6830df3e

Вот мой код

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

for (NSDictionary *dictionary in array) {
    location.latitude = [dictionary[@"latitude"] floatValue];
    location.longitude = [dictionary[@"longitude"] floatValue];

    // Creates a marker in the center of the map.
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.icon = [UIImage imageNamed:(@"marker.png")];
    marker.position = CLLocationCoordinate2DMake(location.latitude, location.longitude);
    bounds = [bounds includingCoordinate:marker.position];
    marker.title = dictionary[@"type"];
    marker.map = mapView_;
}   

[mapView_ animateWithCameraUpdate:[GMSCameraUpdate fitBounds:bounds withPadding:30.0f]];

Любая помощь?

4b9b3361

Ответ 1

- (void)focusMapToShowAllMarkers
{

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

    for (GMSMarker *marker in <An array of your markers>)
        bounds = [bounds includingCoordinate:marker.position];

    [<yourMap> animateWithCameraUpdate:[GMSCameraUpdate fitBounds:bounds withPadding:30.0f]];


}

UPDATE:

Вы уверены, что в вашем массиве маркеров и координат нет ничего плохого? Я пробовал этот код и отлично работает. Я положил это на viewDidAppear

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:[[NSDictionary alloc]initWithObjectsAndKeys:@"44.66",@"latitude",@"21.33",@"longitude", nil],
                         [[NSDictionary alloc]initWithObjectsAndKeys:@"44.66",@"latitude",@"21.453",@"longitude", nil],
                         [[NSDictionary alloc]initWithObjectsAndKeys:@"44.44",@"latitude",@"21.993",@"longitude", nil],
                         [[NSDictionary alloc]initWithObjectsAndKeys:@"44.635",@"latitude",@"21.553",@"longitude", nil],
                         [[NSDictionary alloc]initWithObjectsAndKeys:@"44.3546",@"latitude",@"21.663",@"longitude", nil],
                         [[NSDictionary alloc]initWithObjectsAndKeys:@"44.6643",@"latitude",@"21.212",@"longitude", nil],
                         [[NSDictionary alloc]initWithObjectsAndKeys:@"44.63466",@"latitude",@"21.3523",@"longitude", nil],nil];
GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] init];
CLLocationCoordinate2D location;
for (NSDictionary *dictionary in array)
{
    location.latitude = [dictionary[@"latitude"] floatValue];
    location.longitude = [dictionary[@"longitude"] floatValue];
    // Creates a marker in the center of the map.
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.icon = [UIImage imageNamed:(@"marker.png")];
    marker.position = CLLocationCoordinate2DMake(location.latitude, location.longitude);
    bounds = [bounds includingCoordinate:marker.position];
    marker.title = dictionary[@"type"];
    marker.map = mapView_;
}
[mapView_ animateWithCameraUpdate:[GMSCameraUpdate fitBounds:bounds withPadding:30.0f]];

Это мой результат:

map with markers

Ответ 2

Swift 3 - Xcode 8

var bounds = GMSCoordinateBounds()
        for marker in yourArrayOfMarkers
        {
            bounds = bounds.includingCoordinate(marker.position)
        }
        let update = GMSCameraUpdate.fit(bounds, withPadding: 60)
        mapView.animate(with: update)

Ответ 3

Решение Swift с использованием GMSCoordinateBounds() без пути,

var bounds = GMSCoordinateBounds()
for location in locationArray
{
    let latitude = location.valueForKey("latitude")
    let longitude = location.valueForKey("longitude")

    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude:latitude, longitude:longitude)
    marker.map = self.mapView
    bounds = bounds.includingCoordinate(marker.position)
}
let update = GMSCameraUpdate.fitBounds(bounds, withPadding: 100)
mapView.animateWithCameraUpdate(update)

Ответ 4

Очистить скорость <3 > :

let bounds = markers.reduce(GMSCoordinateBounds()) { 
    $0.includingCoordinate($1.position) 
}

mapView.animate(with: .fit(bounds, withPadding: 30.0))

Ответ 5

@IBOutlet weak var mapView: GMSMapView!

let camera = GMSCameraPosition.cameraWithLatitude(23.0793, longitude:  
72.4957, zoom: 5)
mapView.camera = camera
mapView.delegate = self
mapView.myLocationEnabled = true

*** arry has dictionary object which has value of Latitude and Longitude. ***
let path = GMSMutablePath()

for i in 0..<arry.count {

   let dict = arry[i] as! [String:AnyObject]
   let latTemp =  dict["latitude"] as! Double
   let longTemp =  dict["longitude"] as! Double

   let marker = GMSMarker()
   marker.position = CLLocationCoordinate2D(latitude: latTemp, longitude: longTemp)
   marker.title = "Austrilia"
   marker.appearAnimation = kGMSMarkerAnimationNone
   marker.map = self.mapView

   path.addCoordinate(CLLocationCoordinate2DMake(latTemp, longTemp))

  } 

  let bounds = GMSCoordinateBounds(path: path)
  self.mapView!.animateWithCameraUpdate(GMSCameraUpdate.fitBounds(bounds, withPadding: 50.0))

Ответ 6

Самый простой способ, который я нашел, - создать GMSMutablePath, а затем добавить к нему все координаты ваших маркеров. Затем вы можете использовать инициализатор GMSCoordinateBounds initWithPath: для создания границ.

Как только у вас есть границы, вы можете создать GMSCameraUpdate и использовать его для анимации карты с видимыми границами, содержащими все ваши маркеры.

Например, если у вас есть массив GMSMarker:

NSArray *myMarkers;   // array of marker which sets in Mapview
GMSMutablePath *path = [GMSMutablePath path];

for (GMSMarker *marker in myMarkers) { 
   [path addCoordinate: marker.position];
}
GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] initWithPath:path];

[_mapView animateWithCameraUpdate:[GMSCameraUpdate fitBounds:bounds]];

Ответ 7

Что касается Google Maps версии 2.0.0, если вы попытаетесь создать GMSCoordinateBounds, используя конструктор по умолчанию GMSCoordinateBounds(), и вы проверите флаг "valid", он вернет false и не сделает animateWithCameraUpdate: move.

Решение Swift 2.3

    if let myLocation = mapView.myLocation {
        let path = GMSMutablePath()
        path.addCoordinate(myLocation.coordinate)

        //add other coordinates 
        //path.addCoordinate(model.coordinate)

        let bounds = GMSCoordinateBounds(path: path)
        mapView.animateWithCameraUpdate(GMSCameraUpdate.fitBounds(bounds, withPadding: 40))
    }

Ответ 8

Мы можем найти один и тот же код везде, но убедитесь, что он есть в методе viewDidAppear()

//bounding to a region of markers
GMSCoordinateBounds *bounds =
[[GMSCoordinateBounds alloc] initWithCoordinate:sourceMarker.position coordinate:destMarker.position];
[_mapView moveCamera:[GMSCameraUpdate fitBounds:bounds withPadding:50.0]];

Ответ 9

Вы можете повторить маркеры карт и получить дальнейшую точку на востоке, западе, севере и юге и сделать [[GMSCoordinateBounds alloc] initWithRegion:]

Ответ 10

Согласно документации, GMSCoordinateBounds не может быть видоизменен.

GMSCoordinateBounds является неизменным и не может быть изменен после построения.

- (GMSCoordinateBounds *)includingCoordinate:(CLLocationCoordinate2D)coordinate;
- (GMSCoordinateBounds *)includingBounds:(GMSCoordinateBounds *)other;

Таким образом, мы можем изменить GMSCoordinateBounds, используя вышеуказанные методы, включая Cooordinate: (для расширения координат) и incl.Bounds: (для расширения границ).

Так что код Swift будет выглядеть так:

var gmsBounds = GMSCoordinateBounds()
for coordinate in coordinates {
    let marker = GMSMarker(position: coordinate)
    gmsBounds = gmsBounds.includingCoordinate(position)
    marker.map = mapView
}
mapView.animate(with: GMSCameraUpdate.fit(gmsBounds, withPadding: 30.0))

Дополнительные примечания:

Если вы добавили пользовательский вид маркера, добавьте отступ в качестве ширины вида маркера в дополнение к требуемому заполнению.