加入MapKit librarygit
首先得在項目中加入MapKit,如圖api
![](http://static.javashuo.com/static/loading.gif)
MapView服務器
先增長一個ViewController,我這裏用的storyboard,這個玩意仍是挺好用的,比之前用xib好多了。app
![](http://static.javashuo.com/static/loading.gif)
而後拖一個mapview上去,如:函數
![](http://static.javashuo.com/static/loading.gif)
給新增長的ViewController綁定一個class。首先得增長一個class,從uiViewController繼承下來。這個很簡單,如圖oop
![](http://static.javashuo.com/static/loading.gif)
把新增長的ViewController綁定到這個class,也很easy,發現Xcode仍是挺牛的。就是在右邊Identity inspector裏面的custom class裏面改爲新增長的類,原來是UIViewController。ui
![](http://static.javashuo.com/static/loading.gif)
而後給map view控件綁定一個變量,類型是MKMapViewspa
![](http://static.javashuo.com/static/loading.gif)
而後就初始化mapview,顯示。代碼以下:.net
- - (void)viewDidLoad
- {
- [super viewDidLoad];
-
-
- _mapView.mapType = MKMapTypeStandard;
- _mapView.showsUserLocation = YES;
-
- _mapView.zoomEnabled = YES;
-
-
- CLLocationCoordinate2D pos = {39.931203, 116.395573};
-
- MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(pos,2000, 2000);
- MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:viewRegion];
- [_mapView setRegion:adjustedRegion animated:YES];
-
-
- }
我這裏使用百度座標,找了個座標(直接搜索「百度 座標」),而後在咱們本身的地圖裏顯示。這樣運行一下就能夠看到:code
![](http://static.javashuo.com/static/loading.gif)
Map view delegate 回調
能夠實現協議MKMapViewDelegate, 這樣就會有幾個回調。
- - (void) mapViewWillStartLoadingMap:(MKMapView *)mapView
- {
-
- }
-
- -(void)mapViewDidFinishLoadingMap:(MKMapView *)mapView
- {
-
- }
-
- - (void) mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error
- {
-
- }
獲取設備當前位置而且在地圖中顯示
增長一個按鈕,點擊這個按鈕,將顯示設備當前位置。點擊上面的按鈕將顯示某個固定位置。
![](http://static.javashuo.com/static/loading.gif)
CLLocationManager,首先使用CLLocationManager來獲取設備的當前位置。
代碼也是很簡單
- - (void) getCurPosition
- {
-
- if (locationManager==nil)
- {
- locationManager =[[CLLocationManager alloc] init];
- }
-
-
- if ([CLLocationManager locationServicesEnabled])
- {
- locationManager.delegate=self;
- locationManager.desiredAccuracy=kCLLocationAccuracyBest;
- locationManager.distanceFilter=10.0f;
- [locationManager startUpdatingLocation];
- }
- }
而後實現回調函數
- #pragma mark -- CLLocationManagerDelegate
- - (void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
- {
- if ([locations count] > 0) {
- CLLocation* loc = [locations objectAtIndex:0];
- CLLocationCoordinate2D pos = [loc coordinate];
-
- NSLog(@"locationManager, longitude: %f, latitude: %f", pos.longitude, pos.latitude);
-
- if (show == NO) {
- MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(pos,2000, 2000);
- MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:viewRegion];
- [_mapView setRegion:adjustedRegion animated:YES];
-
- show = YES;
- }
- }
- }
當設備位置變化時,這個函數會被調用。這樣咱們就能夠根據位置來作一些事情了。這個例子裏就在第一次獲取位置的時候更新一下地圖顯示。以設備當前位置爲中心,顯示2000米。
完了。貼一下mapview所在的controller代碼: