I am using a marker to display the users location in my iOS application. I have it working right now but as the user moves it adds additional markers and does not delete the old one. I cannot use mapview clear because that clears all my markers and there is other markers I do not want deleted in the scene. I will attach the code below. Thanks
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
CLLocation *location = [change objectForKey:NSKeyValueChangeNewKey];
mapIcon = @"largemapicon";
GMSMarker *myMarker;
CLLocationCoordinate2D coordi=location.coordinate;
myMarker = nil;
myMarker=[GMSMarker markerWithPosition:coordi];
// marker.snippet = coordinates[@"name"];
myMarker.map = self.mapView;
myMarker.appearAnimation = kGMSMarkerAnimationPop;
UIImage * image = [UIImage imageNamed:mapIcon];
CGSize sacleSize = CGSizeMake(45, 45);
UIGraphicsBeginImageContextWithOptions(sacleSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, sacleSize.width, sacleSize.height)];
UIImage * resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
myMarker.icon = resizedImage;
NSLog(@"movement");
}
To remove the marker you need to keep a reference to it outside this method. If the user's location is always the same marker, simply define it at the class level, and then at the beginning of your observeValueForKeyPath
method, do the following:
myMarker.map = nil;
instead of
myMarker = nil;
Be sure to move your variable declaration (GMSMarker *myMarker;
) out of that method as well. You need it to persist from one call of observeValueForKeyPath
to the next (when the user's location is updated).