---
title: "iPhone之获取当前位置 "
author: "cissco"
date: "2011-09-21T10:12:56Z"
tags: []
categories: ["移动开发"]
slug: "iphone"
draft: false
lastmod: "2011-09-21T10:12:56Z"
id: 1176811
url: "https://cissco.iteye.com/blog/1176811"
---

[![iphone之获取当前位置](http://s13.sinaimg.cn/middle/4adf31eata6337ce4c17c&690 "iphone之获取当前位置")](http://photo.blog.sina.com.cn/showpic.html#blogid=4adf31ea010176hq&url=http://s13.sinaimg.cn/orignal/4adf31eata6337ce4c17c)

首先，加入地图包  
[![iphone之获取当前位置](http://s4.sinaimg.cn/middle/4adf31eata6337de621f3&690 "iphone之获取当前位置")](http://photo.blog.sina.com.cn/showpic.html#blogid=4adf31ea010176hq&url=http://s4.sinaimg.cn/orignal/4adf31eata6337de621f3)

接口代码：

#import &lt;UIKit/UIKit.h&gt;

#import &lt;MapKit/MapKit.h&gt;

 

@interface View30 : UIViewController &lt;CLLocationManagerDelegate,MKMapViewDelegate&gt;

{

MKMapView \*map;

}

 

@end

 

实现代码：

 

 

\- (void)viewDidLoad {

    \[super viewDidLoad];

//创建位置管理器

CLLocationManager \*locationManager = \[\[CLLocationManager alloc] init];

//设置代理

locationManager.delegate=self;

//指定需要的精度级别

locationManager.desiredAccuracy=kCLLocationAccuracyBest;

//设置距离筛选器

locationManager.distanceFilter=500.0f;

//启动位置管理器

\[locationManager startUpdatingLocation];

 

MKCoordinateRegion theRegion = { {0.0, 0.0 }, { 0.0, 0.0 } };

theRegion.center=\[\[locationManager location] coordinate];

\[locationManager release];

 

//设置地图

map=\[\[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];

map.delegate=self;

//是否显示用户的位置信息

map.showsUserLocation=YES;

//向上滚动 

\[map setZoomEnabled:YES];

//横向滚动

\[map setScrollEnabled:YES];

//设置地图范围  越小越精确

theRegion.span.longitudeDelta = 0.05f;

theRegion.span.latitudeDelta = 0.05f;

\[map setRegion:theRegion animated:YES];

\[self.view addSubview:map];

 

}

 

\- (MKAnnotationView \*)mapView:(MKMapView \*)mV viewForAnnotation:(id &lt;MKAnnotation&gt;)annotation

{//注释指针

MKPinAnnotationView \*pinView = nil;

 

static NSString \*defaultPinID = @"mylocation";

pinView = (MKPinAnnotationView \*)\[map dequeueReusableAnnotationViewWithIdentifier:defaultPinID];

if ( pinView == nil ) 

{

pinView = \[\[\[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];

}

pinView.pinColor = MKPinAnnotationColorRed;

pinView.canShowCallout = YES;

pinView.animatesDrop = YES;

\[map.userLocation setTitle:@"我的位置"];

\[map.userLocation setSubtitle:@"小标题"];

return pinView;

}