用到的类 CLGeocoder,用来将输入的地名编码为CLPlacemark,CLPlacemark封装了一地理信息
上代码
- (void)gencodeQuery :(NSString*)place
{
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
//对地理位置进行编码
[geocoder geocodeAddressString:place completionHandler:^(NSArray *placemarks,NSError *error){
for (int i = 0; i != placemarks.count; ++i)
{
CLPlacemark *placemark = placemarks[i];
//地图进行缩放,第一个参数是中心,第二个参数是南北跨度,第三个参数是东西跨度
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(placemark.location.coordinate, 30000, 30000);
[mapView setRegion:region];
//在地图上添加标注,MapLocation是自定义类,实现了MKAnnotation协议
MapLocation *annotation = [[MapLocation alloc]init];
annotation.streetAddress = placemark.thoroughfare;
annotation.city = placemark.locality;
annotation.state = placemark.administrativeArea;
annotation.zip = placemark.postalCode;
annotation.coordinate = placemark.location.coordinate;
//添加标注,添加后回回调MKMapViewDelegate的
//- (MKAnnotationView*)mapView:(MKMapView *)parmMapView viewForAnnotation:(id<MKAnnotation>)annotation
//自定义MapLocation的原因是addAnnotation接收id <MKAnnotation>参数
[mapView addAnnotation:annotation];
}
}];
}
#pragma MKMapViewDelegate
- (MKAnnotationView*)mapView:(MKMapView *)parmMapView viewForAnnotation:(id<MKAnnotation>)annotation
{
MKPinAnnotationView *animationView = (MKPinAnnotationView*)[parmMapView dequeueReusableAnnotationViewWithIdentifier:@"T"];
if(animationView == nil)
animationView = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"T"];
animationView.pinColor = MKPinAnnotationColorGreen;//设置标注的颜色
animationView.animatesDrop = YES;//设置动画
animationView.canShowCallout = YES;//显示详细信息当点击标注的时候
return animationView;
}
自定义的类
@interface MapLocation : NSObject<MKAnnotation>
@property(nonatomic,readwrite) CLLocationCoordinate2D coordinate;
@property(nonatomic,strong) NSString *streetAddress;
@property(nonatomic,strong) NSString *city;
@property(nonatomic,strong) NSString *state;
@property(nonatomic,strong) NSString *zip;
@end
-------------
@implementation MapLocation
- (NSString*)title
{
return@"您的位置!";
}
- (NSString*)subtitle
{
NSString *ret = @"";
ret = [ret stringByAppendingString:self.state];
ret = [ret stringByAppendingString:self.city];
return ret;
}
@end