I'm trying to solve a problem since few days and I've got no good results. I've got a point and a circle on MKMapView. I've got UISlider and want to change size of MKCircle. Size is changed but during resizing this circle flickers and blinks.
Here is my code:
#implementation ViewController {
Annotation *_annotation;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_annotation = [[Annotation alloc] init];
[_annotation setCoordinate: CLLocationCoordinate2DMake(0, 0)];
[self.mapView addAnnotation:_annotation];
[self.mapView setCenterCoordinate:_annotation.coordinate animated:YES];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(_annotation.coordinate, 1000, 1000);
[self.mapView setRegion:region];
[self _addCircleOnCurrentLocationWithRadius:_slider.value];
}
- (IBAction)onSliderChanged:(UISlider *)sender {
[self.mapView removeOverlays:self.mapView.overlays];
[self _addCircleOnCurrentLocationWithRadius:sender.value];
}
- (void)_addCircleOnCurrentLocationWithRadius:(CGFloat)radius {
MKCircle *circle = [MKCircle circleWithCenterCoordinate:_annotation.coordinate radius:radius];
[self.mapView addOverlay:circle level:MKOverlayLevelAboveRoads];
}
#pragma mark - MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
MKPinAnnotationView *view = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"Annotation"];
return view;
}
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay {
MKCircleView *view = [[MKCircleView alloc] initWithCircle:overlay];
view.fillColor = [UIColor redColor];
view.strokeColor = [UIColor blueColor];
view.alpha = 0.3;
return view;
}
#end
I've tried:
removing old overlays and adding new one,
doing as above with NSOperationQueue
Here is a screen recording how it looks like.
I see that is possible to do, Apple did this in Reminders app.
Also I'm familiar with following topics:
Smooth resizing of MKCircle
Moving MKCircle on MKMapview and dragging MKMapview
Smooth resizing of MKCircle
Thank you in advance.
Edit
I've did it. I will add an answer with class which supports resizing today or tomorrow.
I've did it by creating subclass of MKCircleView and override - (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)ctx method. TSCircleView class is shared on github here..
Related
Setting up a map view with annotation of nearby cafes.
But when I try to custom the annotations using MKMarkerAnnotationView, nothing shows on the map view.
and when I log the marker, the frame is (0 0; 0 0);
I tried pin too, still didn't work.
I set up delegate on storyboard already.
I also debugged the view controller there are marker views but it is not displaying them because the width and height are zero ?
- (void)viewDidLoad {
[super viewDidLoad];
[self.cafeMap setShowsUserLocation:YES];
[self.locationManager requestWhenInUseAuthorization];
self.cafes = [NSMutableArray array];
[self fetchData];
[self.cafeMap registerClass:[MKAnnotationView class] forAnnotationViewWithReuseIdentifier:#"marker"];
}
-(void)fetchData{
[self.networkManager fetchCafeData:^(NSArray * _Nonnull businesses) {
for (NSDictionary* cafeInfo in businesses) {
Cafe *cafe = [[Cafe alloc]initWithCafeInfo:cafeInfo];
[self.cafes addObject:cafe];
}
for (Cafe *cafe in self.cafes) {
[self.cafeMap addAnnotation:cafe];
}
[self.cafeMap showAnnotations:self.cafes animated:YES];
}];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
if ([annotation isKindOfClass:[MKUserLocation class]]) {
return nil;
}
MKMarkerAnnotationView *marker = [[MKMarkerAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:#"marker"];
marker = (MKMarkerAnnotationView*) [mapView dequeueReusableAnnotationViewWithIdentifier:#"marker" forAnnotation:annotation];
UIButton *button = [UIButton buttonWithType:UIButtonTypeInfoLight];
marker.rightCalloutAccessoryView = button;
[marker setEnabled:YES];
[marker setCanShowCallout:YES];
NSLog(#"MARKER:%#",marker);
return marker;
}
This is the output:
MARKER:<MKAnnotationView: 0x7f9fa3f333b0; frame = (0 0; 0 0); layer = <CALayer: 0x60000253d220>>
Note that your message says that it is a MKAnnotationView. That is because you have registered MKAnnotationView for your identifier rather than MKMarkerAnnotationView. You want:
[self.cafeMap registerClass:[MKMarkerAnnotationView class] forAnnotationViewWithReuseIdentifier:#"marker"];
As an aside, you should be able to simplify viewForAnnotation to:
MKAnnotationView *marker = [mapView dequeueReusableAnnotationViewWithIdentifier:#"marker" forAnnotation:annotation];
Personally, I’d move the configuration of the annotation view into its own subclass:
static NSString * const cafeClusteringIdentifier = #"cafe";
#interface CafeAnnotationView: MKMarkerAnnotationView
#end
#implementation CafeAnnotationView
- (instancetype)initWithAnnotation:(id<MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier]) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeInfoLight];
self.rightCalloutAccessoryView = button;
self.canShowCallout = true;
self.clusteringIdentifier = cafeClusteringIdentifier;
}
return self;
}
- (void)setAnnotation:(id<MKAnnotation>)annotation {
[super setAnnotation:annotation];
self.clusteringIdentifier = cafeClusteringIdentifier;
}
#end
By doing this, I avoid bloating my view controller with code for configuring annotation views.
Note, I’m setting the clusteringIdentifier so that you enjoy that behavior of the MKMarkerAnnotationView.
And then I’d register that class for MKMapViewDefaultAnnotationViewReuseIdentifier:
[self.cafeMap registerClass:[CafeAnnotationView class] forAnnotationViewWithReuseIdentifier:MKMapViewDefaultAnnotationViewReuseIdentifier];
The benefit of using MKMapViewDefaultAnnotationViewReuseIdentifier is that you don’t have to implement viewForAnnotation at all. Delete your implementation of that method entirely. In iOS 11 and later, you only need to implement viewForAnnotation if you need to do something special like having multiple custom reuse identifiers for multiple types of annotations.
Anyway, that yields:
I am loading the mapview as below, with MKAnnotationView added as subview in the mapview. I have added as subview, instead of addAnnotation, as I wanted the annotation view in the center all the time and the mapview to scroll under it.
- (void)viewDidLoad {
[super viewDidLoad];
self.mapView.delegate = self;
[self.mapView addSubview:self.centerAnnotationView];
}
- (MKPointAnnotation *)centerAnnotaion
{
if (!_centerAnnotaion) {
_centerAnnotaion = [[MKPointAnnotation alloc] init];
_centerAnnotaion.title = #"Title";
}
return _centerAnnotaion;
}
- (MKPinAnnotationView *)centerAnnotationView
{
if (!_centerAnnotationView) {
_centerAnnotationView = [[MKPinAnnotationView alloc] initWithAnnotation:self.centerAnnotaion
reuseIdentifier:#"centerAnnotationView"];
_centerAnnotationView.pinColor = MKPinAnnotationColorGreen;
_centerAnnotationView.canShowCallout = YES;
_centerAnnotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
}
return _centerAnnotationView;
}
I have the following questions.
Is it possible to get the default callout even when I haven't added the pin as annotation to the map view.
Is there a way that I could get - (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view event working in my case.
Should I use the tap gesture to capture the tap on the annotation pin?
Currently, I am having an issue with my project in implementing a custom MKAnnotationView that has multiple custom UIImageViews. So these custom UIImageViews have a clear button on top of them to not have to add gesture recognizers.
As you can see, it would be beneficial to actually tap the MKAnnotationView subviews and have some action happen.
I implemented a protocol for the MKAnnotationView where each image subview within the MKAnnotationView makes a callback to the controller that is the owner of the MKMapView... Heres the code...
PHProfileImageView *image = [[PHProfileImageView alloc] initWithFrame:CGRectMake(newX - radius / 5.0f, newY - radius / 5.0f, width, height)];
[image setFile:[object objectForKey:kPHEventPictureKey]];
[image.layer setCornerRadius:image.frame.size.height/2];
[image.layer setBorderColor:[[UIColor whiteColor] CGColor]];
[image.layer setBorderWidth:2.0f];
[image.layer setMasksToBounds:YES];
[image.profileButton setTag:i];
[image.profileButton addTarget:self action:#selector(didTapEvent:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:image];
- (void)didTapEvent:(UIButton *)button
{
NSLog(#"%#", [self.pins objectAtIndex:button.tag]);
if (self.delegate && [self.delegate respondsToSelector:#selector(didTapEvent:)]) {
[self.delegate JSClusterAnnotationView:self didTapEvent:[self.pins objectAtIndex:button.tag]];
}
}
So as you can see, I already attempt to log the result of the tapped image but nothing :(. Is the way I'm implementing this not the way to go? Am I supposed to have CAShapeLayers or something? Not really sure at this point. Anyone got any ideas?
Edit
Im thinking that I might have to implement a custom callout view. Since a callout view actually adds buttons to its view and can respond to touch events... Not totally sure though because callouts are only shown once the annotation view is tapped. And in this case, the ACTUAL annotation view is the middle label
So I resized the mkannotationview's frame to a much larger frame and apparently all the subviews are actually not within the MKAnnotationView's bounds, so the subviews aren't actually being tapped. Now that Im thinking about this solution, it probably wasn't the best solution.
If anyone has any suggestions rather than adding subviews to a MKAnnotationView to create the view I currently have, that would be great!
For the Custom AnnotationView with Clickable Buttons, you have to create custom AnnotationView SubClass in the Project. For that create a new file.
And add these two methods to the implementation file.
- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event
{
UIView* hitView = [super hitTest:point withEvent:event];
if (hitView != nil)
{
[self.superview bringSubviewToFront:self];
}
return hitView;
}
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event
{
CGRect rect = self.bounds;
BOOL isInside = CGRectContainsPoint(rect, point);
if(!isInside)
{
for (UIView *view in self.subviews)
{
isInside = CGRectContainsPoint(view.frame, point);
if(isInside)
break;
}
}
return isInside;
}
Then go to the ViewController.m file again and modify the viewDidLoad method as this.
- (void)viewDidLoad {
[super viewDidLoad];
self.mapKit.delegate = self;
//Set Default location to zoom
CLLocationCoordinate2D noLocation = CLLocationCoordinate2DMake(51.900708, -2.083160); //Create the CLLocation from user cordinates
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(noLocation, 50000, 50000); //Set zooming level
MKCoordinateRegion adjustedRegion = [self.mapKit regionThatFits:viewRegion]; //add location to map
[self.mapKit setRegion:adjustedRegion animated:YES]; // create animation zooming
// Place Annotation Point
MKPointAnnotation *annotation1 = [[MKPointAnnotation alloc] init]; //Setting Sample location Annotation
[annotation1 setCoordinate:CLLocationCoordinate2DMake(51.900708, -2.083160)]; //Add cordinates
[self.mapKit addAnnotation:annotation1];
}
Now add that custom View to the ViewController.xib.
Now create this delegate method as below.
#pragma mark : MKMapKit Delegate
-(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation
{
AnnotationView *pinView = nil; //create MKAnnotationView Property
static NSString *defaultPinID = #"com.invasivecode.pin"; //Get the ID to change the pin
pinView = (AnnotationView *)[self.mapKit dequeueReusableAnnotationViewWithIdentifier:defaultPinID]; //Setting custom MKAnnotationView to the ID
if ( pinView == nil )
pinView = [[AnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:defaultPinID]; // init pinView with ID
[pinView addSubview:self.customView];
addSubview:self.customView.center = CGPointMake(self.customView.bounds.size.width*0.1f, -self.customView.bounds.size.height*0.5f);
pinView.image = [UIImage imageNamed:#"Pin"]; //Set the image to pinView
return pinView;
}
I also got this answer few months ago from someone posted on Stackoverflow. I modified it to my project as I want. Hope this will do your work.
I have a view controller, where I initialize a mkmapview programatically, and set the view controller to be the delegate of mkmapview. Also, this mapview is added as a subview to scrollview in the view controller class.
I add a mkpolyline to mkmapview, and I have
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
However, viewforoverlay is not called when view controller is loaded, but it is called when I click/touch mapview and drag/move it around
This problem is typically seen if you add the MKOverlay to the MKMapView prior to assigning the delegate. When you add the MKOverlay to the MKMapView, the delegate method mapView:viewForOverlay: is called. If you have not assigned the delegate by that time, you will not see the overlay renderer in the initial render.
Try adding this line after you add your MKPolylineView overlay:
[myMapView setNeedsRedisplay];
This is how I add a route to my map:
-(void)drawRoute
{
...
routeLine = [MKPolyline polylineWithPoints:pointArr count:totalPoints];
[geoMap addOverlay:routeLine];
....
}
-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
{
MKPolylineView *lineView = [[[MKPolylineView alloc] initWithPolyline:overlay] autorelease];
UIColor *lineColor = [[UIColor alloc] initWithRed:0 green:0 blue:0 alpha:1.0];
lineView.fillColor = lineColor;
lineView.strokeColor = lineColor;
[lineColor release];
lineView.lineWidth = 12;
lineView.alpha = 1;
return lineView;
}
Imagine that I have 6 circles. My timer calls first 2 circles in the beginning and overlay them on map view. Then after 2 seconds, it calls other circles and add them on map view. My problem is how to remove previous overlays.I want to see smooth transition for instance radar map.
Make it short, it would like to remove previous overlays and add the new overlays without flickering! Thanks a lot in advance!!.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize mapView;
#synthesize timer;
#synthesize circle1,circle2,circle3,circle4,circle5,circle6;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
CLLocationCoordinate2D zoomLocation1;
zoomLocation1.latitude=29.830071;
zoomLocation1.longitude=-95.319099;
circle1 = [MKCircle circleWithCenterCoordinate:zoomLocation1 radius:15000];
circle1.title=#"first level";
CLLocationCoordinate2D zoomLocation2;
zoomLocation2.latitude=29.830071;
zoomLocation2.longitude=-95.319099;
circle2 = [MKCircle circleWithCenterCoordinate:zoomLocation2 radius:4000];
circle2.title=#"first level";
CLLocationCoordinate2D zoomLocation3;
zoomLocation3.latitude=29.830071;
zoomLocation3.longitude=-95.319099;
circle3 = [MKCircle circleWithCenterCoordinate:zoomLocation3 radius:6000];
circle3.title=#"second level";
CLLocationCoordinate2D zoomLocation4;
zoomLocation4.latitude=29.830071;
zoomLocation4.longitude=-95.319099;
circle4 = [MKCircle circleWithCenterCoordinate:zoomLocation4 radius:18000];
circle4.title=#"second level";
CLLocationCoordinate2D zoomLocation5;
zoomLocation5.latitude=29.830071;
zoomLocation5.longitude=-95.319099;
circle5 = [MKCircle circleWithCenterCoordinate:zoomLocation5 radius:1000];
circle5.title=#"third level";
CLLocationCoordinate2D zoomLocation6;
zoomLocation6.latitude=29.830071;
zoomLocation6.longitude=-95.319099;
circle6 = [MKCircle circleWithCenterCoordinate:zoomLocation6 radius:13000];
circle6.title=#"third level";
MKCoordinateRegion viewRegion=MKCoordinateRegionMakeWithDistance(zoomLocation1, 60*1609, 60*1609);
MKCoordinateRegion adjustedRegion=[mapView regionThatFits:viewRegion];
[mapView setRegion:adjustedRegion animated:YES];
mapView.mapType=MKMapTypeStandard;
[mapView setDelegate:(id)self];
i=0;
}
- (void)viewDidUnload
{
[self setMapView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)drawButton:(id)sender {
timer = [NSTimer scheduledTimerWithTimeInterval:(2.0) target:self selector:#selector(addingOverlay) userInfo:nil repeats:YES];
}
- (void)addingOverlay {
i=i+1;
switch(i%3)
{
case 1:
[mapView removeOverlays: [mapView overlays]];
[mapView addOverlay:circle1];
[mapView addOverlay:circle2];
break;
case 2:
[mapView removeOverlays: [mapView overlays]];
[mapView addOverlay:circle3];
[mapView addOverlay:circle4];
break;
case 3:
[mapView removeOverlays: [mapView overlays]];
[mapView addOverlay:circle5];
[mapView addOverlay:circle6];
break;
}
}
-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay> )overlay
{
MKCircleView *circleView = [[MKCircleView alloc] initWithOverlay:overlay];
if ([overlay.title isEqualToString:#"first level"])
{
circleView.strokeColor = [UIColor redColor];
circleView.lineWidth = 2;
circleView.fillColor=[UIColor yellowColor];
}
else if([overlay.title isEqualToString:#"second level"])
{
circleView.strokeColor = [UIColor whiteColor];
circleView.lineWidth = 2;
circleView.fillColor=[UIColor blackColor];
}
else{
circleView.strokeColor = [UIColor greenColor];
circleView.lineWidth = 2;
circleView.fillColor=[UIColor redColor];
}
return circleView;
}
#end
I just posted this answer to a similar question.
It has a function that I use (drawRangeRings) that draws two circles. In my example, both circles have the same center coordinate, but different radius values, and colors. You could easily change the code to use different center coordinates for each circle if you need that.
Basically, I call drawRangeRings when the center coordinate changes, and it removes the original two circles, and draws two new ones at a different location.
Let me know if this isn't exactly what you needed.
I don't see any flicker when I use this in my app.