利用MKMapView显示自己当前位置的地图

在 ios利用MKMapView实现简单的地图一文中只是介绍了使用最简单的地图,这篇文章主要是介绍怎么把地图显示到自己的当前位置和是地图扩大。下面是我们实现的界面: 位置相当准确,

ios利用MKMapView实现简单的地图一文中只是介绍了使用最简单的地图,这篇文章主要是介绍怎么把地图显示到自己的当前位置和是地图扩大。下面是我们实现的界面:

位置相当准确,和我用google map或得的信息一样。

下面介绍一下实现的过程,是在 ios利用MKMapView实现简单的地图例子的基础上实现的。

首先要获取自己的经纬度,要使用CLLocationManager,CLLocationManager在CoreLocation.framework中,所以先在工程中添加CoreLocation.framework。

然后添加相关代码:

添加CLLocationManagerDelegate协议

    @interface iphone_MapViewController : UIViewController
    <CLLocationManagerDelegate>{
        IBOutlet MKMapView *mapView;
    }

实现代码:

    - (void)viewDidLoad {
        [super viewDidLoad];
        mapView.showsUserLocation=YES;

        CLLocationManager *locationManager = [[CLLocationManager alloc] init];//创建位置管理器
        locationManager.delegate=self;//设置代理
        locationManager.desiredAccuracy=kCLLocationAccuracyBest;//指定需要的精度级别
        locationManager.distanceFilter=1000.0f;//设置距离筛选器
        [locationManager startUpdatingLocation];//启动位置管理器
        MKCoordinateSpan theSpan;
        //地图的范围 越小越精确
        theSpan.latitudeDelta=0.05;
        theSpan.longitudeDelta=0.05;
        MKCoordinateRegion theRegion;
        theRegion.center=[[locationManager location] coordinate];
        theRegion.span=theSpan;
        [mapView setRegion:theRegion];
        [locationManager release];
    }

运行就可以得到如图所示的效果了。

原文地址:https://www.cnblogs.com/chen1987lei/p/1867623.html