0.在xib或者SB中使用mapView要先導入MapKit框架(不是頭文件而是框架),否則會crash
1.地圖用於顯示,要顯示當前位置的大頭針所以要獲得地理位置信息:
_mgr = [[CLLocationManager alloc]init];
[_mgr requestAlwaysAuthorization];
[_mgr startUpdatingLocation];
2.地圖顯示出來不會默認顯示當前的位置,所以要設置地圖到當前位置:
_mapView.userTrackingMode = MKUserTrackingModeFollow;
3.成爲mapView的delete會拿到(MKUserLocation *)userLocation
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
}
3.1使用(MKUserLocation *)userLocation的location進行地理反編碼
[_geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
CLPlacemark *mark = [placemarks firstObject];
userLocation.title = mark.name;
userLocation.subtitle = mark.locality;
}];
3.2iOS8在打開地圖的時候會默認到當前位置,但是iOS7不會,使用以下方法使其來到當前位置:
//這個方法會到以userLocation.location爲中心的位置(經緯度)
[_mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
//以下方法會去到指定位置,指定中心點(經緯度)和跨度,其中跨度也是和經緯的單位相同,指定顯示範圍的大小
MKCoordinateSpan span = MKCoordinateSpanMake(0.001, 0.001);
MKCoordinateRegion regin = MKCoordinateRegionMake(userLocation.location.coordinate, span);
[_mapView setRegion:regin animated:YES];
4.最基本的大頭針操作,自定義一個model類,並遵守協議(不用實現),聲明以下屬性:
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
erty (nonatomic, copy) NSString *subtitle;
5.添加大頭針的方法:
Annotation *anno = [[Annotation alloc] init];
anno.title = @"哈哈哈";
anno.subtitle = @"哈哈哈";
CGFloat latitude = 36.821199;
CGFloat longitude = 116.858776;
anno.coordinate = CLLocationCoordinate2DMake(latitude , longitude);
// 添加大頭針
[self.mapView addAnnotation:anno];