0
votes

I need to display multiple markers on map by latitude and longitude, I tried below code to show two markers. It's working good , but if need to put marker on 20 or 30 locations , I need to alloc and init the GMSMarker that much of times. Is there any other way to show the multiple markers on map without initiating the GMSMarker for every place.

GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(17.4368, 78.4439);

#warning title and snipped must be dynamic
marker.icon = [UIImage imageNamed:@"one.png"];
marker.title = @"Sydney";
marker.snippet = @"Australia";
marker.appearAnimation = kGMSMarkerAnimationPop;
marker.map = _mapView;


GMSMarker *marker1 = [[GMSMarker alloc] init];
marker1.position = CLLocationCoordinate2DMake(17.398932, 78.472718);
marker1.icon = [UIImage imageNamed:@"one.png"];
marker1.map=_mapView;
2
just add the location with array and write a for loop to create multiple marker.HariKrishnan.P

2 Answers

4
votes

Put the data for each marker in an array and then run a loop over them.

NSArray* arrMarkerData = @[
                           @{@"title": @"Sydney", @"snippet": @"Australia", @"position": [[CLLocation alloc]initWithLatitude:17.4368 longitude:78.4439]},
                           @{@"title": @"Other location", @"snippet": @"other snippet", @"position": [[CLLocation alloc]initWithLatitude:17.398932 longitude:78.472718]}
                           ];

for (NSDictionary* dict in arrMarkerData)
{
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.icon = [UIImage imageNamed:@"one.png"];
    marker.position = [(CLLocation*)dict[@"position"] coordinate];
    marker.title = dict[@"title"];
    marker.snippet = dict[@"snippet"];
    marker.appearAnimation = kGMSMarkerAnimationPop;
    marker.map = _mapView;
}
0
votes

For Those who do Swift 5

  let arrMarkerData = [
         [
    "title": "Sydney",
    "snippet": "Australia",
    "position": CLLocationCoordinate2D(latitude: 17.4368, longitude: 78.4439)
],
[
    "title": "Other location",
    "snippet": "other snippet",
    "position": CLLocationCoordinate2D(latitude: 17.398932, longitude: 78.472718)
]
    ]
    
    for dict in arrMarkerData {
        guard let dict = dict as? [AnyHashable : Any] else {
            continue
        }
        let marker = GMSMarker()
        //marker.icon = UIImage(named: "one.png")
        marker.position = (dict["position"] as? CLLocationCoordinate2D)!
        marker.title = dict["title"] as? String
        marker.snippet = dict["snippet"] as? String
        marker.appearAnimation = .pop
        marker.map = mapView
    }