如何在用户当前位置设置引脚位置?

时间:2014-08-14 00:39:07

标签: objective-c annotations location

//.h file
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface MapMain : UIViewController <MKMapViewDelegate>
{
MKMapView *mapView;
CLLocationManager *locationManager;
}

@property (nonatomic, retain) IBOutlet MKMapView *mapView;

-(IBAction)GetLocation:(id)sender;
-(IBAction)SetPin:(id)sender;

@end

//code within .m

- (void)viewDidLoad
{
self.mapView.showsUserLocation = YES;
self.mapView.delegate = self;
[self.mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
// Do any additional setup after loading the view.
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];

}


-(NSString *)deviceLocation {
return [NSString stringWithFormat:@"latitude: %f longitude: %f",    locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
}


-(IBAction)SetPin:(id)sender
{
NSLog(@"%@", [self deviceLocation]);

Pin *newPin = [[Pin alloc]init];
newPin.coordinate = 
newPin.title = @"Title Tester";
newPin.subtitle = @"Sub Tester";
[self.mapView addAnnotation:newPin];

}

在“Set Pin”中,我想将newPin的坐标设置为用户当前位置。我找到了函数“deviceLocation”,但不知道如何调用它并在我的SetPin函数中使用它。

请帮助!!!

1 个答案:

答案 0 :(得分:0)

在MKMapView.h的MKMapViewDelegate部分中查看以下方法

- (void)mapViewWillStartLocatingUser:(MKMapView *)mapView NS_AVAILABLE(10_9, 4_0);
- (void)mapViewDidStopLocatingUser:(MKMapView *)mapView NS_AVAILABLE(10_9, 4_0);
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation NS_AVAILABLE(10_9, 4_0);
- (void)mapView:(MKMapView *)mapView didFailToLocateUserWithError:(NSError *)error NS_AVAILABLE(10_9, 4_0);

具体来说mapView:didUpdateUserLocation:从那里,您可以获取用户位置并为您的心灵内容设置注释。