• iOS,多媒体,地图相关


    1.本地音频播放

    2.本地视频播放

    3.使用UIImagePickerController摄像头拍照,录像,照片库浏览

    4.使用AVFunction,AVCaptureVideoDataOutput实时获得视频流照片,开关闪光灯

    5.高德地图使用和定位

    6.高德地图,地理编码定位和反地理编码  

    本地音频播放

    //ViewController.m文件
    //导入头文件
    #import <AVFoundation/AVFoundation.h>
    #import <MediaPlayer/MediaPlayer.h>
    
    import "ViewController.h"
    @interface ViewController ()
    //AVAudioPlayer要为全局变量才能播放
    @property (strong,nonatomic) AVAudioPlayer *audioPlayer;
    @end
    
    @implementation ViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
        [self.view setBackgroundColor:[UIColor whiteColor]];
        [self.navigationItem setTitle:@"音频"];
    
        //播放音频;注意:如果点击了stop,那么一定要让播放器重新创建,否则会出现一些莫名其面的问题
       [self.getAudioPlayer play]; 
    }
    
    /**
     *创建音频播放器
     *return 音频播放器
     */
    -(AVAudioPlayer *)getAudioPlayer{
        NSString *path=[[NSBundle mainBundle] pathForResource:@"爱的太迟"ofType:@"mp3"];
        NSURL *url=[NSURL fileURLWithPath:path];
        //创建一个播放器
        _audioPlayer=[[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        //音量0.0-1.0之间
        _audioPlayer.volume=0.2;
        //循环次数
        _audioPlayer.numberOfLoops=1;
        //播放位置
        _audioPlayer.currentTime=0.0;
        //声道数
        NSUInteger channels=_audioPlayer.numberOfChannels;//只读属性
        //持续时间
        NSTimeInterval duration=_audioPlayer.duration;//获取持续时间
        //分配播放所需的资源,并将其加入内部播放队列
        [_audioPlayer prepareToPlay];
        return _audioPlayer;
    }
    @end

    本地视频播放

    //ViewController.m文件
    //导入头文件
    #import <AVFoundation/AVFoundation.h>
    #import <MediaPlayer/MediaPlayer.h>
    #import "ViewController.h"
     
    @interface ViewController ()
    //视频播放控制器
    @property (strong,nonatomic) MPMoviePlayerController *moviePlayer;
    @end
    
    @implementation ViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
        [self.view setBackgroundColor:[UIColor whiteColor]];
        [self.navigationItem setTitle:@"视频"];
     
        //播放视频
        [self.getMoviePlayer play];   
    }
    
    /**
     *创建视频控制器
     *return 视频控制器
     */
    -(MPMoviePlayerController *)getMoviePlayer{
        NSString *path=[[NSBundle mainBundle] pathForResource:@"DotA2官方宣传片"ofType:@"mp4"];
        NSURL *url=[NSURL fileURLWithPath:path];
        _moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:url];
        _moviePlayer.view.frame=self.view.frame;
        //自动调整长宽
     _moviePlayer.view.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [self.view addSubview:_moviePlayer.view];
        return _moviePlayer;
    } 
    @end

     //AVPlayerLayer播放视频

       NSString *path=[[NSBundle mainBundle] pathForResource:@"DotA2官方宣传片" ofType:@"mp4"];
        NSURL *videoURL=[NSURL fileURLWithPath:path];
        AVPlayer *player=[AVPlayer playerWithURL:videoURL];
        
        AVPlayerLayer *layer=[AVPlayerLayer playerLayerWithPlayer:player];
        
        layer.videoGravity=AVLayerVideoGravityResizeAspect;
        
        layer.frame=CGRectMake(-80, 80, 480, 320);
        
        layer.backgroundColor=[[UIColor redColor]CGColor];
        
        [self.view.layer addSublayer:layer];
        [player play];

     使用UIImagePickerController摄像头拍照,录像,照片库浏览

    //ViewController.m文件

    //导入头文件,(NSString*)kUTTypeMovie等类型才能引用
    #import <MobileCoreServices/MobileCoreServices.h>
    #import "ViewController.h"
    
    @interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
    //UIImagePickerController拍照和视频录制
    @property (strong,nonatomic) UIImagePickerController *imagePicker;
    //类型1是拍照,2是录像
    @property (assign,nonatomic)  int pickerType;
    @end
     
    @implementation ViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
        [self.view setBackgroundColor:[UIColor whiteColor]];
        self.navigationItem.title=@"拍照视频";
        
        _pickerType=2;
       [self presentViewController:self.startImagePicker.view animated:YES completion:nil];
    }
    
    /**
     *创建UIImagePickerController
     *return UIImagePickerController
     */
    -(UIImagePickerController *)startImagePicker{
        if (!_imagePicker) {
            _imagePicker=[[UIImagePickerController alloc] init];
            //设置imagePicker的来源为摄像头
            _imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
            //设置使用后置摄像头
            _imagePicker.cameraDevice=UIImagePickerControllerCameraDeviceRear;
            if(_pickerType==1){
                //设置摄像头模式为拍照
             _imagePicker.cameraCaptureMode=UIImagePickerControllerCameraCaptureModePhoto;
            }else if (_pickerType==2){
                //视频带有声音模式
                _imagePicker.mediaTypes=@[(NSString*)kUTTypeMovie];
                //设置视频质量
              _imagePicker.videoQuality=UIImagePickerControllerQualityType640x480;
                //设置摄像头模式为录像模式
    
              _imagePicker.cameraCaptureMode=UIImagePickerControllerCameraCaptureModeVideo;
            }
    
            //允许编辑
            _imagePicker.allowsEditing=YES;
            //设置代理
            _imagePicker.delegate=self;
        }
        return _imagePicker;
    }
    
     
    
    //UIImagePickerControllerDelegate代理,完成时
    -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
        //获得类型是拍照还是录像
        NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
        //如果是拍照
        if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
            UIImage *image;
            //如果允许编辑则获得编辑后的照片,否则获取原始图片
            if (self.imagePicker.allowsEditing) {
                image=[info objectForKey:UIImagePickerControllerEditedImage];
            }else{
                image=[info objectForKey:UIImagePickerControllerOriginalImage];
            }
            @try {
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
            }
            @catch (NSException *exception) {
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"完成"message:@"照片保存失败" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
            }
        }else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
            NSURL *url=[info objectForKey:UIImagePickerControllerMediaURL];
            if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([url path])) {
                //视频保存到相簿
                UISaveVideoAtPathToSavedPhotosAlbum([url path], self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
            }
        }
    }
    
    //视频保存后的回调
    - (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
        if (error) {
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"完成"message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK"otherButtonTitles:nil];
            [alert show];
        }else{
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"完成" message:@"视频保存成功." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        }
    }
    @end
    //ViewController.m文件
    //照片库浏览
    #import "ViewController.h"
     
    @interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
    @property (nonatomic,strong) UIImagePickerController *imagePicker;
    @end
    
    @implementation ViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
        [self.view setBackgroundColor:[UIColor whiteColor]];
        self.navigationItem.title=@"照片浏览";
        [self presentViewController:[self.getImagePickerLibrary view] animated:YES completion:nil];
    }
    
    //创建UIImagePickerController
    -(UIImagePickerController *)getImagePickerLibrary{
        _imagePicker=[[UIImagePickerController alloc] init];
        //设置模式为浏览图片库
        _imagePicker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
        //设置代理
        _imagePicker.delegate=self;
        return _imagePicker;
    }
    
    //实现完成时代理
    -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
        //获取没更改的照片
        UIImage *img=[info objectForKey:UIImagePickerControllerOriginalImage];
    //    将图片装换为base64的data,然后转成UTF-8格式,图片质量 0.0 to 1.0.
        NSString *base64Str=[UIImageJPEGRepresentation(img, 0.5) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        NSString *utf8Str=[NSString stringWithUTF8String:[base64Str UTF8String]];
        //base64转UIImage
        NSData *data=[[NSData alloc] initWithBase64EncodedString:utf8Str options:NSDataBase64DecodingIgnoreUnknownCharacters];
        UIImage *base64Image=[UIImage imageWithData:data];
        UIImageView *imgView=[[UIImageView alloc] initWithFrame:self.view.bounds];
        imgView.image=base64Image;
        [self.view addSubview:imgView];
    }
    @end
     

    使用AVFunction,AVCaptureVideoDataOutput实时获得视频流照片,开关闪光灯

    //IdentifyViewController.m文件

    //
    //  IdentifyViewController.m
    //  
    //
    //  Created by Vie on 15/11/19.
    //
    //
    
    #import "TKIdentifyViewController.h"
    #import <AVFoundation/AVFoundation.h>
    
    @interface TKIdentifyViewController ()<AVCaptureVideoDataOutputSampleBufferDelegate>
    @property(nonatomic,strong)AVCaptureSession *captureSession;//负责输入和输出设备之间的数据传递
    @property(nonatomic,strong) AVCaptureDeviceInput*captureDeviceInput;//AVCaptureDevice输入流
    @property(nonatomic,strong)AVCaptureVideoPreviewLayer*captureVideoPreviewLayer;//相机拍摄预览图层
    @property(nonatomic,strong) AVCaptureVideoDataOutput *dataOutPut;
    @property(nonatomic,strong) AVCaptureDevice *captureDevice;//输入设备
    @end
    
    @implementation TKIdentifyViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
    }
    
    -(void)viewWillAppear:(BOOL)animated{
        [super viewWillAppear:animated];
        //创建会话
        self.captureSession=[[AVCaptureSession alloc] init];
        //设置分辨率
        if ([ self.captureSessioncanSetSessionPreset:AVCaptureSessionPreset1280x720]) {
          self.captureSession.sessionPreset=AVCaptureSessionPreset1280x720;
        }else{
         self.captureSession.sessionPreset=AVCaptureSessionPresetiFrame960x540;
        }
       //获得输入设备
        self.captureDevice=[self getCameraDeviceWithPosition:AVCaptureDevicePositionBack];//取得后置摄像头
        if (!self.captureDevice) {
            NSLog(@"取得后置摄像头时出现问题.");
            return;
        }
        NSError *error=nil;
        //根据输入设备初始化输入对象,用于获得输入数据
        self.captureDeviceInput=[AVCaptureDeviceInputdeviceInputWithDevice:self.captureDevice error:&error];
        if (error) {
            NSLog(@"取得设备输入对象时出错,错误原因:%@",error.localizedDescription);
            return;
        }
        //videoDataOutput对象
        self.dataOutPut=[[AVCaptureVideoDataOutput alloc] init];
        dispatch_queue_t queue=dispatch_queue_create("myQueue", NULL);
        [self.dataOutPut setSampleBufferDelegate:self queue:queue];
        self.dataOutPut.videoSettings=[NSDictionary dictionaryWithObject:[NSNumbernumberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey];
    
        //将输入设备添加到会话中
        if([self.captureSession canAddInput:self.captureDeviceInput]){
            [self.captureSession addInput:self.captureDeviceInput];
        }
        
        //将设备输出添加到会话中
        if ([self.captureSession canAddOutput:self.dataOutPut]) {
             [self.captureSession addOutput:self.dataOutPut];
        }
        
        //创建视频预览层,用于实时展示摄像头状态
        self.captureVideoPreviewLayer=[[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
        self.captureVideoPreviewLayer.frame=self.view.layer.bounds;
        //填充模式
     self.captureVideoPreviewLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;
    
        //将视频预览层添加到界面中
        [self.view.layer insertSublayer:self.captureVideoPreviewLayer atIndex:0];
    }
    
    -(void)viewDidAppear:(BOOL)animated{
        [super viewDidAppear:animated];
        [self.captureSession startRunning];
    }
    
     
    -(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{
        UIImage  *img=[self imageFromSampleBuffer:sampleBuffer];
    }
    
    //用AVFoundation捕捉视频帧,很多时候需要把某一帧转换成UIImage,用此函数:
    - (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer {
        // 为媒体数据设置一个CMSampleBuffer的Core Video图像缓存对象
        CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
        // 锁定pixel buffer的基地址
        CVPixelBufferLockBaseAddress(imageBuffer, 0);
        // 得到pixel buffer的基地址
        void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
        // 得到pixel buffer的行字节数
        size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
        // 得到pixel buffer的宽和高
        size_t width = CVPixelBufferGetWidth(imageBuffer);
        size_t height = CVPixelBufferGetHeight(imageBuffer);
    
        // 创建一个依赖于设备的RGB颜色空间
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
        // 用抽样缓存的数据创建一个位图格式的图形上下文(graphics context)对象
        CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8,bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
        // 根据这个位图context中的像素数据创建一个Quartz image对象
        CGImageRef quartzImage = CGBitmapContextCreateImage(context);
        // 解锁pixel buffer
        CVPixelBufferUnlockBaseAddress(imageBuffer,0);
        // 释放context和颜色空间
        CGContextRelease(context);
        CGColorSpaceRelease(colorSpace);
       
        // 用Quartz image创建一个UIImage对象image
        UIImage *image = [UIImage imageWithCGImage:quartzImage];
        // 释放Quartz image对象
        CGImageRelease(quartzImage);
        return (image);
    }
    
    /**
     *  取得指定位置的摄像头
     *
     *  @param position 摄像头位置
     *
     *  @return 摄像头设备
     */
    -(AVCaptureDevice *)getCameraDeviceWithPosition:(AVCaptureDevicePosition)position{
        NSArray *cameras= [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
        for (AVCaptureDevice *camera in cameras) {
            if ([camera position]==position) {
                return camera;
            }
        }
        return nil;
    }
    
    //开关闪光灯
    -(void)openOrCloseTorch:(UIButton *)sender{
        //请求独占设备访问性能,后面打开或关闭闪光灯
        [self.captureDevice lockForConfiguration:nil];
        if(self.captureDevice.torchMode==AVCaptureTorchModeOff){
            //开启闪光灯
            [self.captureDevice setTorchMode:AVCaptureTorchModeOn];
        }else{
            //关闭闪光灯
            [self.captureDevice setTorchMode:AVCaptureTorchModeOff];
        }
        //当打开或关闭闪光灯时,放弃设备独占权
        [self.captureDevice unlockForConfiguration];
    }
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    @end

    高德地图使用和定位

    高德定位失败的原因可能是未对iOS8做适配

    解决方法是:

    1.工程的info.plist添加NSLocationWhenInUseDescription,NSLocationAlwaysUsageDescription字段,不同的字段对应的方法不同

    2.在AppDelegate.m中声明个CLLocationManager私有变量,代码如下:

    @interface AppDelegate()
    {
        UINavigationController *_navController;
        CLLocationManager      *_locationmanager;
    }
    @end
    
    @implementation AppDelegate
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        [UIApplication sharedApplication].idleTimerDisabled = TRUE;
        _locationmanager = [[CLLocationManager alloc] init];
        [_locationmanager requestAlwaysAuthorization];        //NSLocationAlwaysUsageDescription
        [_locationmanager requestWhenInUseAuthorization];     //NSLocationWhenInUseDescription
        _locationmanager.delegate = self;
    }

    //ViewController.h文件

    #import <UIKit/UIKit.h>
    #import <MapKit/MapKit.h>
    @interface ViewController : UIViewController<MKMapViewDelegate,CLLocationManagerDelegate>
    @end

    //ViewController.m文件

    //
    //  ViewController.m
    //  MapDemo
    //
    //  Created by Vie on 15/7/27.
    //  Copyright (c) 2015年 Vie. All rights reserved.
    //
    
    #import "ViewController.h"
    
    @interface ViewController ()
    @property (strong,nonatomic) MKMapView *mapView;
    @property (strong,nonatomic) CLLocationManager *locationManager;
    @end
    
    @implementation ViewController
    @synthesize mapView=_mapView,locationManager=_locationManager;
    - (void)viewDidLoad {
        [super viewDidLoad];
       self.navigationItem.title=@"Map";
        [self.view setBackgroundColor:[UIColor whiteColor]];
        
        _mapView=[[MKMapView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        //显示用户当前的坐标,打开地图有相应的提升
        _mapView.showsUserLocation=YES;
        //设置用户跟踪模式为跟踪用户位置和方向变化
        [_mapView setUserTrackingMode:MKUserTrackingModeFollowWithHeading animated:YES];
        //地图类型,混合地图(默认标注地图)
        //_mapView.mapType=MKMapTypeHybrid;
        //设置地图的代理
        _mapView.delegate=self;
        
       
        
        //定位管理器
        _locationManager=[[CLLocationManager alloc] init];
        //设置代理
        _locationManager.delegate=self;
        //设置定位精度
        _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        //定位频率,每隔多少米定位一次
        //十米定位一次
        CLLocationDistance distance=10.0;
        _locationManager.distanceFilter=distance;
        //启动跟踪定位
        [_locationManager startUpdatingLocation];
        
        //启动方向定位
        [_locationManager startUpdatingHeading];
    
        [self.view addSubview:_mapView];
         //调用地理编码定位方法
        [self positioningName:@"北京市"];
        //调用反地理编码定位方法
        CLLocationCoordinate2D theCoordinate;
        //纬度
        theCoordinate.latitude=22.541832;
        //经度
        theCoordinate.longitude=113.945930;
        [self getNameLocation:theCoordinate];
       }
    
    //地理编码定位(根据名称获取地址坐标)
    -(void)positioningName:(NSString *)strName{
         CLGeocoder *geocoder=[[CLGeocoder alloc] init];
        //根据“北京市”进行地理编码
        [geocoder geocodeAddressString:strName completionHandler:^(NSArray *placemarks, NSError *error) {
            //获取第一个地标
            CLPlacemark *clPlacemark=[placemarks firstObject];
            CLLocationCoordinate2D coordinate=clPlacemark.location.coordinate;
             NSLog(@"经度:%f,纬度:%f",coordinate.longitude,coordinate.latitude);
    //        //定位地标转化为地图的地标
    //        MKPlacemark *mkplacemark=[[MKPlacemark alloc]initWithPlacemark:clPlacemark];
    //        NSDictionary *options=@{MKLaunchOptionsMapTypeKey:@(MKMapTypeStandard)};
    //        MKMapItem *mapItem=[[MKMapItem alloc]initWithPlacemark:mkplacemark];
    //        [mapItem openInMapsWithLaunchOptions:options];
        }];
    
    }
    //反地理编码(根据坐标获取地名)
    -(void)getNameLocation:(CLLocationCoordinate2D)theCoordinate{
        CLLocation *location=[[CLLocation alloc] initWithLatitude:theCoordinate.latitude longitude:theCoordinate.longitude];
        CLGeocoder *geocoder=[[CLGeocoder alloc]init];
        [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
            CLPlacemark *placemark=[placemarks firstObject];
             NSDictionary *addressDic=placemark.addressDictionary;
            NSLog(@"详细信息:%@",placemark.addressDictionary);
        }];
    
    }
    
    //方向位置改变代理
    -(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading{
        CGFloat heading=newHeading.magneticHeading;
        NSLog(@"%f",heading);
    }
    
    //响应注解按钮轻击事件
    -(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control{
        MKPointAnnotation *annotation=view.annotation;
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.baidu.com"]];
    }
    
    //添加注解后,一点构建视图并将其添加到地图上就会通知该委托
    -(void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray<MKAnnotationView *> *)views{
        for (MKPinAnnotationView *mkaview in views) {
            if ([mkaview.annotation.title isEqualToString:@"深圳思迪"]) {
                //设置图钉颜色,以及是否显示一个按钮
                mkaview.pinColor=MKPinAnnotationColorRed;
                UIButton *button=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
                mkaview.rightCalloutAccessoryView=button;
                //设置提示左侧图片
                UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
                imgView.image=[UIImage imageNamed:@"15.jpg"];
                mkaview.leftCalloutAccessoryView=imgView;
            }
        }
    }
    
    //位置改变代理
    -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
        CLLocation *location=[locations firstObject];//取出第一个位置
        CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标
        NSLog(@"经度:%f,纬度:%f,海拔:%f,航向:%f,行走速度:%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
        //定义经纬坐标(标注点)
        CLLocationCoordinate2D theCoordinate;
        //纬度
        theCoordinate.latitude=coordinate.latitude;
        //经度
        theCoordinate.longitude=coordinate.longitude;
        
        //定义地图显示的范围,经纬度
        MKCoordinateSpan theSpan;
        //纬度
        theSpan.latitudeDelta=0.1;
        //经度
        theSpan.longitudeDelta=0.1;
        
        //定义一个区域(用定义的经纬度和范围来定义)
        MKCoordinateRegion theRegion;
        theRegion.center=theCoordinate;
        theRegion.span=theSpan;
        
        //在地图上显示
        [_mapView setRegion:theRegion];
        
        //用户位置注解,点击定位的标识展示
        _mapView.userLocation.title=@"Me";
        _mapView.userLocation.subtitle=[NSString stringWithFormat:@"经度:%f,纬度:%f",coordinate.longitude,coordinate.latitude];
        
        //移除原来的注释(大头针)
        [_mapView removeAnnotations:_mapView.annotations];
        //注释对象位于指定的点(大头针)
        MKPointAnnotation *annotaion=[[MKPointAnnotation alloc]init];
        //注释点得位置
        annotaion.coordinate=theCoordinate;
        //注释点得主标题
        annotaion.title=@"深圳思迪";
        //副标题
        annotaion.subtitle=@"致力于金融服务的IT公司";
        //地图上添加注释
        [_mapView addAnnotation:annotaion];
        
        
        //如果不需要实时定位,使用完即使关闭定位服务
    //    [_locationManager stopUpdatingLocation];
    }
    @end

    高德地图,地理编码定位和反地理编码  

    //地理编码定位(根据名称获取地址坐标)

    -(void)positioningName:(NSString *)strName{
         CLGeocoder *geocoder=[[CLGeocoder alloc] init];
        //根据“北京市”进行地理编码
        [geocoder geocodeAddressString:@"北京市" completionHandler:^(NSArray*placemarks, NSError *error) {
            //获取第一个地标
            CLPlacemark *clPlacemark=[placemarks firstObject];
    
            //定位地标转化为地图的地标
            MKPlacemark *mkplacemark=[[MKPlacemarkalloc]initWithPlacemark:clPlacemark];
            NSDictionary *options=@{MKLaunchOptionsMapTypeKey:@(MKMapTypeStandard)};
            MKMapItem *mapItem=[[MKMapItem alloc]initWithPlacemark:mkplacemark];
            [mapItem openInMapsWithLaunchOptions:options];
    
        }];
    }

    //反地理编码(根据坐标获取地名)

    -(void)getNameLocation:(CLLocationCoordinate2D)theCoordinate{
        CLLocation *location=[[CLLocation alloc] initWithLatitude:theCoordinate.latitude longitude:theCoordinate.longitude];
        CLGeocoder *geocoder=[[CLGeocoder alloc]init];
        [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray*placemarks, NSError *error) {
            CLPlacemark *placemark=[placemarks firstObject];
             NSDictionary *addressDic=placemark.addressDictionary;
            NSLog(@"详细信息:%@",placemark.addressDictionary);
        }];
    }

    //调用地理编码定位方法

    [self positioningName:@"BEIJING"];

    //调用反地理编码定位方法

    CLLocationCoordinate2D theCoordinate;
    
    //纬度
    
    theCoordinate.latitude=39.54;
    
    //经度
    
    theCoordinate.longitude=116.28;
    
    [self getNameLocation:theCoordinate];
  • 相关阅读:
    Btrace入门到熟练小工完全指南
    mysqldump常用于MySQL数据库逻辑备份
    thrift总结
    十大技巧优化Android App性能
    Google 发布 Android 性能优化典范
    Android性能优化之一:ViewStub
    Android实战技巧:ViewStub的应用
    安装andriod studio时出现Internal error. Please report to https://code.google.com/p/an
    Android Service的生命周期
    Android 70道面试题汇总不再愁面试
  • 原文地址:https://www.cnblogs.com/douniwanxia/p/5894980.html
Copyright © 2020-2023  润新知