MKMapview place pin at location (long/lat)

后端 未结 6 1693
说谎
说谎 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:26

    This assumes that you have ARC enabled and that you have included the MapKit framework.

    First create a class that implements the MKAnnotation protocol. We'll call it MapPinAnnotation.

    MapPinAnnotation.h

    @interface MapPinAnnotation : NSObject 
    
    @property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
    @property (nonatomic, readonly) NSString* title;
    @property (nonatomic, readonly) NSString* subtitle;
    
    - (id)initWithCoordinates:(CLLocationCoordinate2D)location
                    placeName:(NSString *)placeName
                  description:(NSString *)description;
    
    @end
    

    MapPinAnnotation.m

    @implementation MapPinAnnotation
    
    @synthesize coordinate;
    @synthesize title;
    @synthesize subtitle;
    
    - (id)initWithCoordinates:(CLLocationCoordinate2D)location
                    placeName:(NSString *)placeName
                  description:(NSString *)description;
    {
      self = [super init];
      if (self)
      {    
        coordinate = location;
        title = placeName;
        subtitle = description;
      }
    
      return self;
    }
    
    @end
    

    Then add the annotation to the map using the following:

    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(34.421496,
                                                                  -119.70182);
    
    MapPinAnnotation* pinAnnotation = 
      [[MapPinAnnotation alloc] initWithCoordinates:coordinate
                                          placeName:nil
                                        description:nil];
    [mMapView addAnnotation:pinAnnotation];
    

    The containing class will have to implement the MKMapViewDelegate protocol. In particular you will have to define the following function to draw the pin:

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

    In this example the MKAnnotation title and subtitle member variables are not used, but they can be displayed in the delegate function.

提交回复
热议问题