我在XCode中创建了一个可以放大用户位置的工作地图(显然,对于该程序,它默认为Apple总部等)
这是" MyLocationViewController:"
的实现文件#import "MyLocationViewController.h"
@interface MyLocationViewController ()
@end
@implementation MyLocationViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.mapView.showsUserLocation = YES;
self.mapView.delegate = self;
}
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion mapRegion;
mapRegion.center = mapView.userLocation.coordinate;
mapRegion.span.latitudeDelta = 0.001;
mapRegion.span.longitudeDelta = 0.001;
[mapView setRegion:mapRegion animated: YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
这是我上一个文件的头文件:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface MyLocationViewController : UIViewController
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@end
现在,我的问题是:
我想反向对用户的当前位置进行地理编码,提供街道(数字和设置,如果适用),城市和州等信息。优选地,我希望在放大过程完成后自动显示它,显示在蓝点的顶部。然而,在咨询了苹果指南以反转地理编码之后,我仍然对如何做到这一点感到困惑,并且搜索并没有证明太富有成效。
请注意:我希望此反向地理编码程序显示为用户位置之上的地址。用户不应该输入内容并在屏幕外的某个位置单击按钮以查看地址是什么 - 它应该是自动的。
哦,顺便说一下,我不是Objective-C的专家。我几周前刚开始做这种事情,所以请不要在我的问题上抛弃复杂的术语。它让我无处可去。
答案 0 :(得分:2)
我刚刚编写了这个简单的函数,它将从mapView获取用户的位置,并尝试对其进行反向地理编码。代码和评论非常简单。如果您有疑问,请告诉我。
- (void)reverseGeocodeUserLocation {
// create your geocoder object
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
// get the user's location from the map view
CLLocation *userLocation = self.mapView.userLocation.location;
// tell the geocoder to reverse geocode the user's location
[geocoder reverseGeocodeLocation:userLocation completionHandler:^(NSArray *placemarks, NSError *error) {
// if there was an error
if (error) {
// handle error here...
return;
}
// get the first "placemark" object from the result array
CLPlacemark *firstPlacemark = [placemarks firstObject];
// get the address dictionary from the placemark object
NSDictionary *addressDictionary = firstPlacemark.addressDictionary;
// break the dictionary into components for display if you'd like
NSString *street = addressDictionary[@"Street"];
NSString *city = addressDictionary[@"City"];
NSString *state = addressDictionary[@"State"];
NSString *zip = addressDictionary[@"Zip"];
}];
}
我模拟了一个位置来测试它,坐标是42.9897,-71.45435,(有点靠近我的位置),我从第一个地标对象得到的结果字典是:
{
City = Manchester;
Country = "United States";
CountryCode = US;
FormattedAddressLines = (
"274 Merrimack St",
"Manchester, NH 03103-4721",
"United States"
);
PostCodeExtension = 4721;
State = NH;
Street = "274 Merrimack St";
SubAdministrativeArea = Hillsborough;
SubLocality = "East End";
SubThoroughfare = 274;
Thoroughfare = "Merrimack St";
ZIP = 03103;
}