地图定位

//ViewController.m

import "ViewController.h"

import

import

@interface ViewController ()
{
//定义变量地图视图、定位管理对象、地图解析对象
MKMapView *mv;
CLLocationManager *manager;
CLGeocoder *geo;
}
@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    //初始化地图视图
    mv = [[MKMapView alloc]initWithFrame:self.view.bounds];
    mv.mapType = MKMapTypeStandard;
    mv.zoomEnabled = YES;
    mv.rotateEnabled = YES;
    mv.scrollEnabled = YES;
    mv.showsUserLocation = YES;
    [self.view addSubview:mv];
    //定位
    CLLocationCoordinate2D center = {34,101};
    MKCoordinateSpan span = {0.01,0.01};
    MKCoordinateRegion region = {center,span};
    [mv setRegion:region animated:YES];
    //初始化定位管理器
    manager = [[CLLocationManager alloc]init];
    [manager requestWhenInUseAuthorization];
    manager.delegate = self;
    manager.desiredAccuracy = kCLLocationAccuracyBest;
    manager.distanceFilter = kCLDistanceFilterNone;
    [manager startUpdatingLocation];
    //初始化地址解析对象
    geo = [[CLGeocoder alloc]init];
    }

//定位更新响应方法

  • (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
    {
    //获取当前位置
    CLLocation *loc = [locations lastObject];
    //定位
    CLLocationCoordinate2D center = {loc.coordinate.latitude,loc.coordinate.longitude};
    MKCoordinateSpan span = {0.01,0.01};
    MKCoordinateRegion region = {center,span};
    [mv setRegion:region animated:YES];
    NSMutableString *mSt = [NSMutableString string];
    //反向解析经纬度获取地址
    [geo reverseGeocodeLocation:loc completionHandler:^(NSArray * _Nullable placemarks, NSError * _Nullable error) {
    CLPlacemark *pla = [placemarks firstObject];

      NSArray *arr = [pla.addressDictionary objectForKey:@"FormattedAddressLines"];
      //拼接地址
      for (NSString *str in arr) {
          [mSt appendString:str];
      }
      //添加锚点
      MKPointAnnotation *anno = [[MKPointAnnotation alloc]init];
      anno.coordinate = center;
      anno.title = @"我的位置";
      anno.subtitle = mSt;
      [mv addAnnotation:anno];
    

    }];
    }

  • (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
    {
    CLLocationCoordinate2D loc = [userLocation coordinate];
    //放大地图到自身的经纬度位置。
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 250, 250);
    [mv setRegion:region animated:YES];
    }

  • (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation
    {
    static NSString *cellid = @"cellid";
    MKAnnotationView *anno = [mapView dequeueReusableAnnotationViewWithIdentifier:cellid];
    if (!anno) {
    anno = [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:cellid];
    }
    anno.canShowCallout = YES;
    return anno;
    }

你可能感兴趣的:(地图定位)