How do I take a pair of latitude,longitude floats and get the MKMapView to drop a pin and display the location?
Given a pair of floats for latitude and longitude, and a MapView, how do I get the MapView to drop a pin in the location and "zoom" the screen to display the loc开发者_开发技巧ation?
I've read through some of the SO posts and they all seem to be about specific aspects of this, but I haven't been able to "put them together" in my head.
Thanks very much! -Frank
The sample app WorldCities shows how you can zoom into a given location but it doesn't drop a pin there. Another sample app called MapCallouts does drop pins but it doesn't zoom.
The zoom part is easy (see didChooseWorldCity method in WorldCities).
To drop a pin, you have to send the addAnnotation message to the mapview and send it an object that implements the MKAnnotation protocol. So first you need to create a class that implements MKAnnotation. Here's an example called MyMapPin:
//MyMapPin.h...
#import <MapKit/MapKit.h>
@interface MyMapPin : NSObject <MKAnnotation> {
CLLocationCoordinate2D coordinate;
NSString *subtitle;
NSString *title;
}
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic,retain) NSString *subtitle;
@property (nonatomic,retain) NSString *title;
- (id) initWithCoords:(CLLocationCoordinate2D) coords;
@end
//MyMapPin.m...
#import "MapPin.h"
@implementation MyMapPin
@synthesize coordinate;
@synthesize subtitle;
@synthesize title;
- (id) initWithCoords:(CLLocationCoordinate2D) coords {
self = [super init];
if (self != nil) {
coordinate = coords;
}
return self;
}
- (void) dealloc
{
[title release];
[subtitle release];
[super dealloc];
}
@end
Now you could modify the WorldCities sample by adding this code at the beginning of the animateToPlace method:
MyMapPin *pin = [[MyMapPin alloc] initWithCoords:worldCity.coordinate];
[mapView addAnnotation:pin];
[pin release];
worldCity.coordinate in the WorldCities app is just a property of type CLLocationCoordinate2D which has two fields latitude and longitude. The two floats would go in there.
Note the addAnnotation will just put a pin at the city. To get an animated dropping pin, you also have to implement the viewForAnnotation method and set animatesDrop to YES. See an example in MapViewController.m in MapCallouts. Also set the mapview's delegate to wherever the viewForAnnotation method is implemented (usually self/File's Owner).
精彩评论