emotality emotality - 4 months ago 17
iOS Question

Google Maps markers not removing iOS

I'm running a thread to fetch drivers location every 10 seconds and want to remove the added markers from the map but it doesn't work..

My code:

-(void)APiResponse:(id)returnJson
{
[googleMapsDriverPin setMap:nil];
googleMapsDriverPin = nil;

NSMutableArray *driverPins = [[NSMutableArray alloc]init];
for (int x = 0; x < [[returnJson valueForKey:@"drivers"] count]; x++) {
CLLocation *driverLocations = [[CLLocation alloc]initWithLatitude:[[[[returnJson valueForKey:@"drivers"] objectAtIndex:x] valueForKey:@"driver_latitude"] doubleValue] longitude:[[[[detail valueForKey:@"drivers"] objectAtIndex:x] valueForKey:@"driver_longitude"] doubleValue]];
[driverPins addObject:driverLocations];
}

for (CLLocation *newLocation in driverPins) {
googleMapsDriverPin = [[GMSMarker alloc] init];
[googleMapsDriverPin setPosition:newLocation.coordinate];
[googleMapsDriverPin setAnimated:YES];
[googleMapsDriverPin setTitle:@"title"];
[googleMapsDriverPin setSnippet:@"snippet"];
[googleMapsDriverPin setIcon:[GMSMarker markerImageWithColor:[UIColor blackColor]]];
[googleMapsDriverPin setMap:googleMaps];
}
}


It just keeps adding and adding every 10 seconds and not removing, please help!
Thanks!

Answer

Its a kind of quick and dirty option but if you wanted to go that way GMSMarker has a userData property which you could use to tag the driver pins

- (void)apiResponse:(id)returnJson
{        
    for (GMSMarker *pin in self.googleMaps.markers) {
        if (pin.userData == @"Driver Pin"){ 
            pin.map = nil; 
        }
    }

    ...

    for (CLLocation *newLocation in driverPins) {
        googleMapsDriverPin = [[GMSMarker alloc] init];
        ...
        [googleMapsDriverPin setUserData:@"Driver Pin"];
    }
}

Update:

[self.googleMapsView clear];