IOS——地图的使用、地图定位到当前位置(包括ios8获取位置)、地图标注的添加、地图放大缩小监听


1. 地图的使用

(1).在项目中导入frame MapKit.framework

(2). 在.h文件中添加 

@interface TestView :UIViewController{

   IBOutletMKMapView *mapView;

}

@property (retain,nonatomic)IBOutletMKMapView *mapView;


(3). 在.m文件中实现mapView

    CGRect rx = [UIScreenmainScreen].bounds;

    mapView=[[MKMapViewalloc]initWithFrame:rx];

    [self.viewaddSubview:mapView];


2. 地图上定位到当前位置

(1). 在.h文件中

#import <CoreLocation/CoreLocation.h>

< CLLocationManagerDelegate>

    CLLocationManager *locationManager;


(2).  在.m文件中(前提已经实现了地图)

<1> 在ViewdidLoad中实现代码

  1. locationManager = [[CLLocationManager alloc] init];  
  2.     locationManager.delegate = self;  
  3.     [locationManager startUpdatingLocation];  
<2> 实现locationManger方法获取当前位置的经纬度,并在地图上移动到相应位置

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    //定位成功后在地图上移动到当前位置
    [locationManager stopUpdatingLocation];
    
    NSString *strLat = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.latitude];
    NSString *strLng = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.longitude];
    NSLog(@"Lat: %@  Lng: %@", strLat, strLng);
    
    CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(newLocation.coordinate.latitude,newLocation.coordinate.longitude);
    float zoomLevel = 0.02;
    MKCoordinateRegion region = MKCoordinateRegionMake(coords,MKCoordinateSpanMake(zoomLevel, zoomLevel));
    [mapView setRegion:[mapView regionThatFits:region] animated:YES];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"locError:%@", error);
    
}

2. IOS8获取当前位置

(1). 首先在Info.plist文件中添加key为NSLocationWhenInUseUsageDescription,value为空的字符串

(2). 添加重写方法:


- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {

    switch (status) {

        casekCLAuthorizationStatusNotDetermined:

            if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {

                [locationManager requestWhenInUseAuthorization];

            }

            break;

        default:

            break;

    }

}


(3). 在启动locationManager前添加方法:


    if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {

        [locationManager requestWhenInUseAuthorization];

    }

    mapView.showsUserLocation =YES;

    

    [locationManager startUpdatingLocation];

   


3. 地图标注的添加

在实现地图的基础上,实现过个地图标注

(1). 在实现地图的ViewController实现接口 MKMapViewDelegate

(2). 地图标注类需要自定义,创建MapPoint类,实现接口<MKAnnotation>

MapPoint.h 文件


#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface MapPoint : NSObject <MKAnnotation>
@property (nonatomic,readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic,copy) NSString *title;
-(id)initWithCoordinate:(CLLocationCoordinate2D)c andTitle:(NSString*)t;
@end



MapPoint.m 文件

#import "MapPoint.h"
@implementation MapPoint
@synthesize coordinate;
@synthesize title;

-(id)initWithCoordinate:(CLLocationCoordinate2D)c andTitle:(NSString *)t{
    self = [super init];
    if(self){
        coordinate = c;
        title = t;
    }
    return self;
}

@end

这样,该地图标注可以在点击的时候显示其Title


(3). 下面是在地图上实现标注的方法addPointsToMap,调用时直接[self addPointsToMap]即可

我的数据是从数据库检出的,所以添加和删除地图标注都是动态的,优化方法稍后提供。


-(void)addPointsToMap{
    
    NSMutableArray *dataX=[[NSMutableArray alloc] init];
    NSMutableArray *dataY=[[NSMutableArray alloc] init];
    NSMutableArray *buildingName=[[NSMutableArray alloc]init];
	//Check data from DB
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status) {
        NSLog(@"Please open your location service");
    } else {
        NSString *dbFilePath = [[NSBundle mainBundle] pathForResource:@"Building" ofType:@"db"];
        if (sqlite3_open([dbFilePath UTF8String], &database) == SQLITE_OK)
        {
            NSString * selectSql = [NSString stringWithFormat:@"select * from building where (abs(x-%f)<=250) and (abs(y-%f)<=250)",20,20];
            sqlite3_stmt *statement;
            sectionsArray = [[NSMutableArray alloc]init];
            if (sqlite3_prepare_v2(database, [selectSql UTF8String], -1, &statement, nil)==SQLITE_OK)
            {
                while (sqlite3_step(statement)==SQLITE_ROW)//SQLITE_OK SQLITE_ROW
                {
                    int x=sqlite3_column_int(statement, 0);
                    int y=sqlite3_column_int(statement,1);
                    NSString *name=[[NSString alloc] initWithCString:(char *)sqlite3_column_text(statement, 2) encoding:NSUTF8StringEncoding];
                    NSNumber *locationX=[NSNumber numberWithInt:x];
                    NSNumber *locationY=[NSNumber numberWithInt:y];;
                    [dataX addObject:locationX];
                    [dataY addObject:locationY];
                    [buildingName addObject:name];
                }
            }
        }
        else {
            sqlite3_close(database);
        }
    }
    
    NSMutableArray *points=[[NSMutableArray alloc] init];
    for (int i=0;i<dataX.count;i++){
        int y=[[dataY objectAtIndex:i] intValue];
        int x=[[dataX objectAtIndex:i] intValue];
        double locationLac=(y-1000)*0.0000023903;
        double locationLong=(x-1000)*0.0000068494;
        //Show data from the map
        CLLocationCoordinate2D coor = CLLocationCoordinate2DMake(locationLac, locationLong);
        MapPoint *mapPoint = [[[MapPoint alloc]initWithCoordinate:coor andTitle:[buildingName objectAtIndex:i]] autorelease];
        [points addObject:mapPoint];
    }
	//Add Points to map 
    [mapView addAnnotations:points];
}

(4). 下面的代理方法是地图标注点击事件的监听方法,可以通过该方法进行相关操作

我的操作是点击后地图消失,并将点击选中的标注地址(title值)显示在text中

#pragma mapview delegate
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    mapBackgroundView.hidden=YES;
    if ([view isKindOfClass:[MKPinAnnotationView class]]){
        MapPoint* p = (MapPoint*)(view.annotation);
        buildingTextField.text=p.title;
    }
}

4. 地图放大缩小事件监听

先调用第一个方法,然后再调用第二个方法

//移动、缩放地图
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
}
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    
    MKCoordinateRegion region;
    CLLocationCoordinate2D centerCoordinate = mapView.region.center;
    region.center= centerCoordinate;
    
    mapLat=centerCoordinate.latitude;
    mapLng=centerCoordinate.longitude;
    [mapView removeAnnotations:mapView.annotations];
    [self addPointsToMap];
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值