Toggling MapKit Overlays On/Off by pressing the same button?
I have a MapView with a toolbar button that when pushed adds overlays to the MapView. What I would like is for the button (IBAction) to check to see if there already are overlays on the map and if there are remove, if there are not, to add them.
My current code that adds the overlays is as follows:
- (IBAction)waterWaysAction:(id)sender
{
NSLog(@"WaterWays pushed");
if ([mapView overlays]) {
[mapView removeOverlays:[mapView overlays]];
NSLog(@"WaterWays removed");
} else {
// ******* adds the overlays for the waterways **********
// inner harbor
CLLocationCoordinate2D innerHarborPoints[13] = {
CLLocationCoordinate2DMake(43.02313691051886, -87.90539558418189),
CLLocationCoordinate2DMake(43.0213450482963, -87.90596442438722),
CLLocationCoordinate2DMak开发者_运维问答e(43.01721422337822, -87.90249007832719),
CLLocationCoordinate2DMake(43.0141641230024, -87.90402523886414),
CLLocationCoordinate2DMake(43.00858391833174, -87.8971780500095),
CLLocationCoordinate2DMake(43.016711699807, -87.90156448365555),
CLLocationCoordinate2DMake(43.01692320142091, -87.90093306118753),
CLLocationCoordinate2DMake(43.02204743639911, -87.90385746629964),
CLLocationCoordinate2DMake(43.02400128319255, -87.90186558765494),
CLLocationCoordinate2DMake(43.02441284233703, -87.89897827382163),
CLLocationCoordinate2DMake(43.02564995691736, -87.89925323299293),
CLLocationCoordinate2DMake(43.02549123239004, -87.90378517804325),
CLLocationCoordinate2DMake(43.02313691051886, -87.90539558418189)};
MKPolygon *innerHarborPolygon = [MKPolygon polygonWithCoordinates:innerHarborPoints count:13];
innerHarborPolygon.title = @"Inner Harbor";
[mapView addOverlay:innerHarborPolygon];
NSLog(@"WaterWays added");
}
}
This code works one time to add the overlay, and one time to remove it. After that (from viewing Log output) it appears as though the function (button) thinks the MapView still has overlays on it, and therefore it needs to keep removing them (even though they aren't there anymore).
Thanks in advance for any help!
Try checking the count
of the overlays array instead:
if ([[mapView overlays] count] > 0) {
Without checking the count
, the overlays
array can be not-nil but have no objects.
精彩评论