MKMapview place pin at location (long/lat)

后端 未结 6 1705
说谎
说谎 2021-02-01 06:31

I have latitude and long values and I need to be able to drop a pin at this location.

Can anybody provide some advice on how to go about this?

6条回答
  •  广开言路
    2021-02-01 07:22

    You should:
    1. add the MapKit framework to your project. 2. create a class which implements the MKAnnotation protocol.
    Sample:

    Annotation.h

    @interface Annotation : NSObject  {
        NSString *_title;
        NSString *_subtitle;
    
        CLLocationCoordinate2D _coordinate;
    }
    
    // Getters and setters
    - (void)setTitle:(NSString *)title;
    - (void)setSubtitle:(NSString *)subtitle;
    
    @end
    

    Annotation.m

    @implementation Annotation
    
    #pragma mark -
    #pragma mark Memory management
    
    - (void)dealloc {
        [self setTitle:nil];
        [self setSubtitle:nil];
    
        [super dealloc];
    }
    
    #pragma mark -
    #pragma mark Getters and setters
    
    - (NSString *)title {
        return _title;
    }
    
    - (NSString *)subtitle {
        return _subtitle;
    }
    
    - (void)setTitle:(NSString *)title {    
        if (_title != title) {
            [_title release];
            _title = [title retain];
        }
    }
    
    - (void)setSubtitle:(NSString *)subtitle {
        if (_subtitle != subtitle) {
            [_subtitle release];
            _subtitle = [subtitle retain];
        }
    }
    
    - (CLLocationCoordinate2D)coordinate {
        return _coordinate;
    }
    
    - (void)setCoordinate:(CLLocationCoordinate2D)newCoordinate {
        _coordinate = newCoordinate;
    }
    
    @end
    

    2. create an instance of this class and set the lat/lon property
    3. add the instance to the MKMapView object with this method:

    - (void)addAnnotation:(id)annotation
    

    4. You should set the delegate of the map and implement the following method:

    - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id )annotation {
        if ([annotation isKindOfClass:[MKUserLocation class]]) {
            return nil;
        }
    
        static NSString* ShopAnnotationIdentifier = @"shopAnnotationIdentifier";
        MKPinAnnotationView *pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:ShopAnnotationIdentifier];
        if (!pinView) {
            pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:ShopAnnotationIdentifier] autorelease];
            pinView.pinColor = MKPinAnnotationColorRed;
            pinView.animatesDrop = YES;
        }
        return pinView;
    }
    

提交回复
热议问题