问题
So according to the documentation, I need to keep a reference to the marker. Right now, in my viewWillDisappear
method I'm trying to clear one of the pins off the map but it's not working. Maybe it's because I don't have a reference to it? If so, how does that work? (By the way, I couldn't get it to work as a part of any other method as well, not just viewWillDisappear
.)
I have the latitude and longitude of the marker and here's what I'm doing now:
CLLocationCoordinate2D position = CLLocationCoordinate2DMake([[passedCoordinates objectAtIndex:0]doubleValue], [[passedCoordinates objectAtIndex:1]doubleValue]);
GMSMarker *marker = [GMSMarker markerWithPosition:position];
marker.map = nil;
But it's not clearing. Any advice?
Update:
I'm keeping a reference now and this is how I'm trying to find which marker to clear:
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:YES];
if (passedCoordinates.count != 0) {
for (GMSMarker *markerRef in _markerRefs){
if (markerRef.position.latitude == [[passedCoordinates objectAtIndex:0]doubleValue] && markerRef.position.longitude == [[passedCoordinates objectAtIndex:1] doubleValue]) {
NSLog(@"here");
markerRef.map = nil;
}
}
}
}
I get the log output that it's finding the correct marker but it's not going away. I added a button on the navigation bar just to click and remove the marker with the same function but it's still on the map.
回答1:
When you call markerWithPosition:
its creating a new object with given position. It will not return your old marker object's pointer with that position.
When you creating your markers, you should keep it in an array:
@interface YourClass() // Declaring array that will hold all markers @property (strong, nonatomic) NSMutableArray *allMarkers; //... @end @implementation //... - (void)yourMethod { if (!self.allMarkers) { self.allMarkers = [[NSMutableArray alloc] init]; } // Here, when you creating your markers and adding to self.mapView CLLocationCoordinate2D position = CLLocationCoordinate2DMake([[passedCoordinates objectAtIndex:0]doubleValue], [[passedCoordinates objectAtIndex:1]doubleValue]); GMSMarker *marker = [GMSMarker markerWithPosition:position]; marker.map = self.mapView; // add allocated markers to allMarkers array [self.allMarkers addObject:marker] } //... - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; for (GMSMarker *marker in self.allMarkers) { // Remove marker from the map marker.map = nil; } }
来源:https://stackoverflow.com/questions/24343769/how-to-keep-a-reference-of-marker-in-ios-google-maps