获取当前用户所在位置的地址

发布于 2024-12-11 08:21:55 字数 3427 浏览 6 评论 0原文

我遵循一些教程并混合了我糟糕的代码。现在我可以获得我当前的位置。当我点击按钮时,它会触发位于我当前位置的图钉。如果我点击图钉,该消息会显示我当前的地址。

我有两个问题:

  1. 为什么我无法获得更精确的地址?现在我收到的地址包含国家、城市和地区,但没有道路名称。

  2. 如何获取当前位置地址的“文本”?我想在其他地方的 UILabel 中显示地址,但不知道该怎么做。

非常感谢!

这是 .h

#import <UIKit/UIKit.h>
#import "MapKit/MapKit.h"
#import "CoreLocation/CoreLocation.h"

@interface UserLocationAddressViewController : UIViewController     <MKMapViewDelegate,MKReverseGeocoderDelegate>
{
    MKMapView *userLocationAddMapView;
    CLLocationManager *locationManager;
}

@property (nonatomic, retain) MKMapView *userLocationAddMapView;

-(IBAction)getUserLocationAddress:(id)sender;

@end

这是 .m

#import "UserLocationAddressViewController.h"

@implementation UserLocationAddressViewController

@synthesize userLocationAddMapView;

-(IBAction)getUserLocationAddress:(id)sender
{
    MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:locationManager.location.coordinate];
    geoCoder.delegate = self;
    [geoCoder start]; 
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)dealloc
{
    [userLocationAddMapView release];
    [super dealloc];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

self.userLocationAddMapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    userLocationAddMapView.showsUserLocation = YES;
    userLocationAddMapView.delegate = self;
    self.userLocationAddMapView.mapType = MKMapTypeStandard;

    locationManager = [[CLLocationManager alloc] init];
    [locationManager startUpdatingLocation];
    CLLocationCoordinate2D coordinate = locationManager.location.coordinate;

    MKCoordinateRegion mapRegion;
    mapRegion.center = coordinate;
    MKCoordinateSpan mapSpan;
    mapSpan.latitudeDelta = 0.006;
    mapSpan.longitudeDelta = 0.006;
    mapRegion.span = mapSpan;
    [userLocationAddMapView setRegion:mapRegion animated:YES];
    self.userLocationAddMapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.userLocationAddMapView];

    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Get Add" style:UIBarButtonItemStylePlain target:self action:@selector(getUserLocationAddress:)] autorelease];  
}

-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
    NSLog(@"placemark %f %f", placemark.coordinate.latitude, placemark.coordinate.longitude);
    NSLog(@"addressDictionary %@", placemark.addressDictionary);
    [userLocationAddMapView addAnnotations:[NSArray arrayWithObjects:placemark, nil]];
    [geocoder release];
}

-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
    NSLog(@"reverseGeocoder fail");
    [geocoder release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

I follow some tutorial and mix my awful code. Now I can get my current location. And when I tap on a button it will trigger a pin which locates on my current location. If I tap on the pin, the message shows address of my current.

I have two question:

  1. Why I can not get a more precise address? Now I receive address with country, city and district, but without name of the road.

  2. How can I get the "text" of the address of current location? I want to display the address in a UILabel elsewhere but don't know how to do that.

Thank you very much!

here's the .h

#import <UIKit/UIKit.h>
#import "MapKit/MapKit.h"
#import "CoreLocation/CoreLocation.h"

@interface UserLocationAddressViewController : UIViewController     <MKMapViewDelegate,MKReverseGeocoderDelegate>
{
    MKMapView *userLocationAddMapView;
    CLLocationManager *locationManager;
}

@property (nonatomic, retain) MKMapView *userLocationAddMapView;

-(IBAction)getUserLocationAddress:(id)sender;

@end

And Here's .m

#import "UserLocationAddressViewController.h"

@implementation UserLocationAddressViewController

@synthesize userLocationAddMapView;

-(IBAction)getUserLocationAddress:(id)sender
{
    MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:locationManager.location.coordinate];
    geoCoder.delegate = self;
    [geoCoder start]; 
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)dealloc
{
    [userLocationAddMapView release];
    [super dealloc];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

self.userLocationAddMapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    userLocationAddMapView.showsUserLocation = YES;
    userLocationAddMapView.delegate = self;
    self.userLocationAddMapView.mapType = MKMapTypeStandard;

    locationManager = [[CLLocationManager alloc] init];
    [locationManager startUpdatingLocation];
    CLLocationCoordinate2D coordinate = locationManager.location.coordinate;

    MKCoordinateRegion mapRegion;
    mapRegion.center = coordinate;
    MKCoordinateSpan mapSpan;
    mapSpan.latitudeDelta = 0.006;
    mapSpan.longitudeDelta = 0.006;
    mapRegion.span = mapSpan;
    [userLocationAddMapView setRegion:mapRegion animated:YES];
    self.userLocationAddMapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.userLocationAddMapView];

    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Get Add" style:UIBarButtonItemStylePlain target:self action:@selector(getUserLocationAddress:)] autorelease];  
}

-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
    NSLog(@"placemark %f %f", placemark.coordinate.latitude, placemark.coordinate.longitude);
    NSLog(@"addressDictionary %@", placemark.addressDictionary);
    [userLocationAddMapView addAnnotations:[NSArray arrayWithObjects:placemark, nil]];
    [geocoder release];
}

-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
    NSLog(@"reverseGeocoder fail");
    [geocoder release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

源来凯始玺欢你 2024-12-18 08:21:55

你不应该真正使用 MKReverseGeocoder,因为它已经被苹果在 iOS5 中贬值,你真的应该使用 CLGeocoder。下面的示例将返回基于 NSArray *placemarks 的一整吨信息,然后您可以迭代它们并调用 assoc 数组中的键。

#import "MapPoint.h"

@implementation MapPoint
@synthesize coordinate, title, dateAdded, subtitle, city, reverseGeo;

-(id)initWithCoordinates:(CLLocationCoordinate2D)c 
                   title:(NSString *)t {

    self = [super init];
    if (self) {

        coordinate = c;
        [self setTitle: t];
        [self setCurrentCity: [[CLLocation alloc] initWithLatitude:c.latitude longitude:c.longitude]];

        [self setDateAdded: [[NSDate alloc] init]];

    }
    return self;

}

-(void)setCurrentCity: (CLLocation *)loc {

    if (!self.reverseGeo) {
        self.reverseGeo = [[CLGeocoder alloc] init];
    }

    [self.reverseGeo reverseGeocodeLocation: loc completionHandler: 
     ^(NSArray *placemarks, NSError *error) {

         for (CLPlacemark *placemark in placemarks) {

             NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
             [formatter setTimeStyle:NSDateFormatterNoStyle];
             [formatter setDateStyle:NSDateFormatterLongStyle];

             NSString *dateString = [formatter stringFromDate: [self dateAdded]];
             [self setSubtitle: [dateString stringByAppendingString: [placemark locality] ] ];             

         }
     }];
}

@end

You shouldn't really use MKReverseGeocoder as it has been depreciated by apple in iOS5, you should really use CLGeocoder. The following example will return a whole tonne of information which is based in the NSArray *placemarks, you can then iterate through them and call the keys in the assoc array.

#import "MapPoint.h"

@implementation MapPoint
@synthesize coordinate, title, dateAdded, subtitle, city, reverseGeo;

-(id)initWithCoordinates:(CLLocationCoordinate2D)c 
                   title:(NSString *)t {

    self = [super init];
    if (self) {

        coordinate = c;
        [self setTitle: t];
        [self setCurrentCity: [[CLLocation alloc] initWithLatitude:c.latitude longitude:c.longitude]];

        [self setDateAdded: [[NSDate alloc] init]];

    }
    return self;

}

-(void)setCurrentCity: (CLLocation *)loc {

    if (!self.reverseGeo) {
        self.reverseGeo = [[CLGeocoder alloc] init];
    }

    [self.reverseGeo reverseGeocodeLocation: loc completionHandler: 
     ^(NSArray *placemarks, NSError *error) {

         for (CLPlacemark *placemark in placemarks) {

             NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
             [formatter setTimeStyle:NSDateFormatterNoStyle];
             [formatter setDateStyle:NSDateFormatterLongStyle];

             NSString *dateString = [formatter stringFromDate: [self dateAdded]];
             [self setSubtitle: [dateString stringByAppendingString: [placemark locality] ] ];             

         }
     }];
}

@end
偏爱自由 2024-12-18 08:21:55

只需放置这个委托方法,我希望这可以帮助你。

-- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
    NSLog(@"MKReverseGeocoder has failed.");

}

-- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
    currentLocation = [placemark.locality stringByAppendingFormat:@", "];
    currentLocation = [currentLocation stringByAppendingString:placemark.country];
    [indicator stopAnimating];
    txtLocation.text = currentLocation;

}

Just place this delegate methods, I hope this may help you.

-- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
    NSLog(@"MKReverseGeocoder has failed.");

}

-- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
    currentLocation = [placemark.locality stringByAppendingFormat:@", "];
    currentLocation = [currentLocation stringByAppendingString:placemark.country];
    [indicator stopAnimating];
    txtLocation.text = currentLocation;

}
怀中猫帐中妖 2024-12-18 08:21:55

我遇到了同样的问题,MKReverseGeocoder 并不总是返回完整的地址,因为有时坐标不够准确并且服务无法生成近似地址。
为了获得最佳结果,我针对雅虎实施了其他反向地理编码。所以基本上如果 MKReverseGeocoder (google) 没有返回完整的地址,我会查询 yahoo 谁可以生成一个近似的地址。

另一方面要小心 MKReverseGeocoder,它在 IOS 5 中已被弃用,他们建议使用 CLGeocoder 代替

I have got the same issue, MKReverseGeocoder doesn't always return the full address, beacause sometimes the coordinates is not accurate enough and the service can't generate an approximative address.
In order to get best results i have implemented an other reverse geocoding against yahoo. So basically if MKReverseGeocoder (google) doesn't return a full address, i query yahoo who can generate an approximative one.

On the other hand be carreful with MKReverseGeocoder it has been deprecated in IOS 5, they recommand to use CLGeocoder instead

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文