1. 程式人生 > >位置與地圖(三)給地圖加入覆蓋層

位置與地圖(三)給地圖加入覆蓋層

urn water rec load res img nsbundle 邊框顏色 http

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
    self.mapView.mapType = MKMapTypeStandard;
    self.mapView.scrollEnabled = YES;
    //  設置地圖不可旋轉
    self.mapView.rotateEnabled = NO;
    self.mapView.zoomEnabled = YES;
    self.mapView.showsUserLocation = YES;
    
    //  設置地圖中心的經緯度
    CLLocationCoordinate2D center = {39.910650,116.47030};
    //  設置地圖顯示的範圍,數值越小細節越清楚
    MKCoordinateSpan span = {0.01,0.01};
    //  二者合一設置顯示區域
    MKCoordinateRegion region = {center,span};
    [self.mapView setRegion:region animated:YES];

    [self.view addSubview:self.mapView];
    
    UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [self.mapView addGestureRecognizer:longGesture];
    
    //  設置代理
    self.mapView.delegate = self;
    
}

- (void)longPress:(UILongPressGestureRecognizer *)longGesture{
    
    //  獲取長按點得坐標
    CGPoint postion = [longGesture locationInView:self.mapView];
    //  將長按點坐標轉換為經緯度
    CLLocationCoordinate2D coord2D = [self.mapView convertPoint:postion toCoordinateFromView:self.mapView];
    //  創建一個圓形覆蓋層對象
    MKCircle *circle = [MKCircle circleWithCenterCoordinate:coord2D radius:100];
    //  將單個的覆蓋層加入到指定的層級
    [self.mapView addOverlay:circle level:MKOverlayLevelAboveLabels];
    
}

//  該方法返回的MKOverlayRenderer負責繪制覆蓋層控件
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay{

    MKCircle *circle = (MKCircle *)overlay;
    // iOS7之後,推薦使用MKXxxRenderer來負責渲染覆蓋層控件
    MKCircleRenderer *circleRend = [[MKCircleRenderer alloc] initWithCircle:circle];
    circleRend.alpha = 0.3;
    //  填充顏色
    circleRend.fillColor = [UIColor blueColor];
    //  邊框顏色
    circleRend.strokeColor = [UIColor redColor];
    
    return circleRend;
}


/*********iOS7新增的MKTileOverlay覆蓋層*******************************************
- (void)longPress:(UILongPressGestureRecognizer *)longGesture{
    
    //  指定本地圖片覆蓋
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"hmt" withExtension:@"png"];
    MKTileOverlay *tileOverlay = [[MKTileOverlay alloc] initWithURLTemplate:[url description]];
    [self.mapView addOverlay:tileOverlay];
    
}

//  該方法返回的MKOverlayRenderer負責繪制覆蓋層控件
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay{
    
    MKTileOverlayRenderer *tileRender = [[MKTileOverlayRenderer alloc] initWithOverlay:(MKTileOverlay *)overlay];
    tileRender.alpha = 0.2;
    return circleRend;
}
*/
技術分享

位置與地圖(三)給地圖加入覆蓋層