时尚地图

IOS之地图和定位应用开发

11.1 iOS定位服务

11.2 iOS地图

11.3 Web地图

11.1 iOS定位服务

iOS中有三个定位服务组件:

Wifi定位,通过查询一个Wifi路由器的地理位置的信息。比较省电,iPod touch和iPad也可以采用。

蜂窝基站定位,通过移动运用商基站定位。也适合有3G版本的iPod touch和iPad。

GPS卫星定位,通过3-4颗GPS定位位置定位,最为准确,但是耗电量大,不能遮挡。

Core Location

Core Location是iPhone、iPad等开发定位服务应用程序的框架。我们要在Xcode中添加“CoreLocation.framework”存在的框架。

主要使用的类是:CLLocationManager,通过CLLocationManager实现定位服务。

CoreLocation.framework

定位服务实例

项目WhereAmI:

WhereAmIViewController.h

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface ViewController : UIViewController<CLLocationManagerDelegate> {
    CLLocationManager* locationManager;
}

@property (strong, nonatomic)    CLLocationManager* locationManager;
@property (retain, nonatomic) IBOutlet UILabel *longitudeText;
@property (retain, nonatomic) IBOutlet UILabel *latituduText;
@property (retain, nonatomic) IBOutlet UIActivityIndicatorView *activity;
- (IBAction)findMe:(id)sender;
- (IBAction)webMap:(id)sender;

@end

CLLocationManagerDelegate是定位服务的委托,常用的位置变化回调方法是:

locationManager:didUpdateToLocation:fromLocation: locationManager:didFailWithError:

CLLocationManager 是定位服务管理类,通过它可以设置定位服务的参数、获取经纬度等。

m中加载方法

- (IBAction)findMe:(id)sender {
    self.locationManager = [[[CLLocationManager alloc] init] autorelease];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 1000.0f;
    [self.locationManager startUpdatingLocation];
    [activity startAnimating];
    NSLog(@"start gps");
}

CLLocationManager 是的startUpdatingLocation方法启动所有定位硬件,对应的方法是stopUpdatingLocation,通过调用该方法关闭定位服务器更新,为了省电必须在不用的时候调用该方法关闭定位服务。

此外,我们还可以在这里设定定位服务的参数,包括:distanceFilter和desiredAccuracy。

distanceFilter,这个属性用来控制定位服务更新频率。单位是“米”。 desiredAccuracy,这个属性用来控制定位精度,精度

越高耗电量越大。

定位精度 

desiredAccuracy精度参数可以iOS SDK通过常量实现:

kCLLocationAccuracyNearestTenMeters,10米

kCLLocationAccuracyHundredMeters ,100米

kCLLocationAccuracyKilometer ,1000米

kCLLocationAccuracyThreeKilometers,3000米

kCLLocationAccuracyBest ,最好的精度

kCLLocationAccuracyBestForNavigation,导航情况下最好精度,iOS 4 SDK新增加。一般要有外接电源时候才能使用。

委托方法用于实现位置的更新

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    latituduText.text = [NSString stringWithFormat:@"%3.5f",newLocation.coordinate.latitude];
    longitudeText.text = [NSString stringWithFormat:@"%3.5f",newLocation.coordinate.longitude];
    [activity stopAnimating];
    [locationManager stopUpdatingLocation];
    NSLog(@"location ok");
}

该委托方法不仅可以获得当前位置(newLocation),还可以获得上次的位置(oldLocation ),CLLocation 对象coordinate.latitude属性获得经度,coordinate.longitude属性获得纬度。

[NSString stringWithFormat:@"%3.5f”, newLocation.coordinate.latitude]  中的%3.5f是输出整数部分是3位,小数部分是5位的浮点数。

11.2 iOS地图

iOS应用程序中使用Map Kit API开发地图应用程序。

其核心是MKMapView类使用。

多数情况下地图会与定位服务结合使用。

地图开发一般过程

添加MapKit类库

MapKit.framework

MapMeViewController.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "MapLocation.h"

@interface ViewController : UIViewController<CLLocationManagerDelegate, MKReverseGeocoderDelegate, MKMapViewDelegate> {

}

@property (retain, nonatomic) IBOutlet MKMapView *mapView;
@property (retain, nonatomic) IBOutlet UIActivityIndicatorView *activity;
- (IBAction)findMe:(id)sender;
@end

CLLocationManagerDelegate是定位服务委托。

MKMapViewDelegate是地图视图委托,主要方法:

-mapView:viewForAnnotation:

-mapViewDidFailLoadingMap:withError:

MKReverseGeocoderDelegate是给地理坐标获得标志点信息的委托,用于地理信息编码(即:从坐标获得地点获得信息),主要委托方法:

– reverseGeocoder:didFindPlacemark:

– reverseGeocoder:didFailWithError:

m文件中的视图加载和卸载

- (void)viewDidLoad {
    [super viewDidLoad];
    mapView.mapType = MKMapTypeStandard;
    //mapView.mapType = MKMapTypeSatellite;
    //mapView.mapType = MKMapTypeHybrid;
    mapView.delegate = self;
}

mapView.mapType = MKMapTypeStandard;是指定地图的类型,iOS提供了三种风格的地图:

MKMapTypeStandard标准地图模式

MKMapTypeSatellite卫星地图模式

MKMapTypeHybrid具有街道等信息的卫星地图模式

mapView.delegate = self;是将委托对象指定为自身。

按钮事件

- (IBAction)findMe:(id)sender {
    CLLocationManager *lm = [[CLLocationManager alloc] init];
    lm.delegate = self;
    lm.desiredAccuracy = kCLLocationAccuracyBest;
    [lm startUpdatingLocation];

    activity.hidden = NO;
    [activity startAnimating];
}

点击按钮时候通过定位服务获取当前位置信息。

通过lm.delegate = self;是将委托对象指定为自身。

因此,点击事件发生时候将会回调CLLocationManagerDelegate委托的

-locationManager:didUpdateToLocation:fromLocation:方法。

回调位置更新方法

#pragma mark CLLocationManagerDelegate Methods
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {

    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 2000, 2000);
    //[mapView setRegion:viewRegion animated:YES];
    MKCoordinateRegion adjustedRegion = [mapView regionThatFits:viewRegion];
    [mapView setRegion:adjustedRegion animated:YES];

    manager.delegate = nil;
    [manager stopUpdatingLocation];

    MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
    geocoder.delegate = self;
    [geocoder start];
}

MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 2000, 2000); 该函数能够创建一个MKCoordinateRegion结构体,第一个参数是一个CLLocationCoordinate2D结构指定了目标区域的中心点,第二个是目标区域南北的跨度单位是米,第三个是目标区域东西的跨度单位是米。后两个参数的调整会影响地图缩放。

[[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate]; 创建地理编码对象geocoder,通过该对象可以把坐标转换成为地理信息的描述。

geocoder.delegate = self;指定编码的处理是自身对象。

[geocoder start];开始编码处理。

MKReverseGeocoderDelegate

是地理编码委托对象,该委托的方法:

成功时候调用-reverseGeocoder:didFindPlacemark:

失败时候调用-reverseGeocoder:didFailWithError:

成功编码回调方法

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {

    MapLocation *annotation = [[MapLocation alloc] init];
    annotation.streetAddress = placemark.thoroughfare;
    annotation.city = placemark.locality;
    annotation.state = placemark.administrativeArea;
    annotation.zip = placemark.postalCode;
    annotation.coordinate = geocoder.coordinate;
    [mapView addAnnotation:annotation];    

    [annotation release];
    geocoder.delegate = nil;
    [geocoder autorelease];

    [activity stopAnimating];
    activity.hidden = YES;
}

成功编码后需要在该方法中创建标注对象(MapLocation)。MapLocation 是我们自定义的实现MKAnnotation协议标注对象。 该方法的placemark是MKPlacemark获得很多地理信息,详细见下表。

[mapView addAnnotation:annotation]; 为地图添加标注,该方法将会触发mapView:viewForAnnotation:方法回调。

MKPlacemark类属性

addressDictionary  地址信息的dictionary

thoroughfare  指定街道级别信息

subThoroughfare  指定街道级别的附加信息

locality  指定城市信息

subLocality  指定城市信息附加信息

administrativeArea  行政区域

subAdministrativeArea  行政区域附加信息

country  国家信息

countryCode  国家代号

postalCode  邮政编码

失败编码回调方法

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"地理解码错误息"
                          message:@"地理代码不能识别"
                          delegate:nil
                          cancelButtonTitle:@"Ok"
                          otherButtonTitles:nil];
    [alert show];
    [alert release];

    geocoder.delegate = nil;
    [geocoder autorelease];

    [activity stopAnimating];
}

MKMapViewDelegate

是地图视图委托对象,本例子我们使用的方法:

- mapView:viewForAnnotation:为地图设置标注时候回调方法。

-mapViewDidFailLoadingMap:withError:地图加载错误时候回调方法。

地图标注回调方法

#pragma mark Map View Delegate Methods
- (MKAnnotationView *) mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>) annotation {

    MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"PIN_ANNOTATION"];
    if(annotationView == nil) {
        annotationView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation
                                                          reuseIdentifier:@"PIN_ANNOTATION"] autorelease];
    }
    annotationView.canShowCallout = YES;
    annotationView.pinColor = MKPinAnnotationColorRed;
    annotationView.animatesDrop = YES;
    annotationView.highlighted = YES;
    annotationView.draggable = YES;
    return annotationView;
}

与表格视图单元格处理类似,地图标注对象由于会很多,因此需要重复利用,通过

dequeueReusableAnnotationViewWithIdentifier方法可以查找可重复利用的标注对象,以达到节省内存的目的。

annotationView.canShowCallout = YES;指定标注上的插图,点击图钉有气泡显示。

annotationView.pinColor 设置图钉的颜色。

annotationView.animatesDrop动画效果。

地图加载失败回调方法

- (void)mapViewDidFailLoadingMap:(MKMapView *)theMapView withError:(NSError *)error {
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"地图加载错误"
                          message:[error localizedDescription]
                          delegate:nil
                          cancelButtonTitle:@"Ok"
                          otherButtonTitles:nil];
    [alert show];
    [alert release];
}

自定义地图标注对象 

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface MapLocation : NSObject <MKAnnotation, NSCoding> {
    NSString *streetAddress;
    NSString *city;
    NSString *state;
    NSString *zip;

    CLLocationCoordinate2D coordinate;
}
@property (nonatomic, copy) NSString *streetAddress;
@property (nonatomic, copy) NSString *city;
@property (nonatomic, copy) NSString *state;
@property (nonatomic, copy) NSString *zip;
@property (nonatomic, readwrite) CLLocationCoordinate2D coordinate;
@end

作为地图标注对象实现MKAnnotation协议是必须的,只有实现该协议才能使该类成为标注类。实现NSCoding协议是可选的,实现该协议可以使标注对象能够复制。 里面的属性有哪些要看你自己的需要。

MapLocation.m

- (NSString *)title {
    return @"您的位置!";
}
- (NSString *)subtitle {

    NSMutableString *ret = [NSMutableString string];
    if (streetAddress)
        [ret appendString:streetAddress];
    if (streetAddress && (city || state || zip))
        [ret appendString:@" • "];
    if (city)
        [ret appendString:city];
    if (city && state)
        [ret appendString:@", "];
    if (state)
        [ret appendString:state];
    if (zip)
        [ret appendFormat:@", %@", zip];

    return ret;
}

title 和subtitle 是MKAnnotation协议要求实现的方法。

MapLocation.m

#pragma mark -
- (void)dealloc {
    [streetAddress release];
    [city release];
    [state release];
    [zip release];
    [super dealloc];
}
#pragma mark -
#pragma mark NSCoding Methods
- (void) encodeWithCoder: (NSCoder *)encoder {
    [encoder encodeObject: [self streetAddress] forKey: @"streetAddress"];
    [encoder encodeObject: [self city] forKey: @"city"];
    [encoder encodeObject: [self state] forKey: @"state"];
    [encoder encodeObject: [self zip] forKey: @"zip"];
}
- (id) initWithCoder: (NSCoder *)decoder  {
    if (self = [super init]) {
        [self setStreetAddress: [decoder decodeObjectForKey: @"streetAddress"]];
        [self setCity: [decoder decodeObjectForKey: @"city"]];
        [self setState: [decoder decodeObjectForKey: @"state"]];
        [self setZip: [decoder decodeObjectForKey: @"zip"]];
    }
    return self;
}

encodeWithCoder:和initWithCoder:是NSCoding协议要求实现方法。

11.3 Web地图

在iOS中我们还可以使用Web地图。

- (IBAction)webMap:(id)sender {
    CLLocation *lastLocation = [locationManager location];
    if(!lastLocation)
    {
        UIAlertView *alert;
        alert = [[UIAlertView alloc]
                 initWithTitle:@"系统错误"
                 message:@"还没有接收到数据!"
                 delegate:nil cancelButtonTitle:nil
                 otherButtonTitles:@"OK", nil];

        [alert show];
        [alert release];
        return;
    }

    NSString *urlString = [NSString stringWithFormat:
                           @"http://maps.google.com/[email protected]%f,%f",
                           lastLocation.coordinate.latitude,
                           lastLocation.coordinate.longitude];
    NSURL *url = [NSURL URLWithString:urlString];

    [[UIApplication sharedApplication] openURL:url];
}

http://maps.google.com/[email protected]%f,%f是请求Web地图的网站,q后面上参数。

[[UIApplication sharedApplication] openURL:url];打开iOS内置的浏览器,即在内置浏览器中打开地图。

注: 
1 本教程是基于关东升老师的教程 
2 基于黑苹果10.6.8和xcode4.2 
3 本人初学,有什么不对的望指教 
4 教程会随着本人学习,持续更新 
5 教程是本人从word笔记中拷贝出来了,所以格式请见谅

时间: 2024-08-01 17:57:01

时尚地图的相关文章

时尚地图1

[转载]IOS地图开发与定位 (2013-03-05 16:38:20) 转载▼ 原文地址:IOS地图开发与定位作者:哭吧晗 来源:http://blog.csdn.net/zhuiyi316/article/details/8306615 首先我们需要一个视图去呈现地图,苹果自带一个关于地图视图的类,名字叫MKMapView,可以在MapKit这个框架找到,所以用到地图需要在头文件中#import ,这样大家已经可以看到一个地图了,可以拖拽以及缩放. 下面是重点介绍如何去操作地图. 在这里我想

百度地图与 高德导航

概述 百度地图是百度提供的一项网络地图搜索服务,用户可以查询街道,商场,楼盘的位置,也可以找到自己附近的餐馆,学校,公园,银行等,高德导航是一款为车主用户提供的安全.易用.高效的离线手机导航软件,产品覆盖所有手机平台. 一简介 百度地图是百度提供的一项网络地图搜索服务,覆盖了国内近400多个城市,数千个区县,在百度地图里,用户可以快速定位到自己的位置,搜索周边美食娱乐,不但可以帮你找位置,还能帮你到哪去,公交,驾车,步行三种出行方式任你选择!还有蚯蚓路线.免费语音导航.时间胶囊让你出行无忧. 高

百度地图技术大揭秘

在优亿开放日上,我们邀请过众多产品.运营方面的专家,但是工程师可能比较少一点,这次的活动,我们很高兴请到了百度地图高级研发工程师游东.游东具有四年以上的地图和导航开发经验,目前主要负责百度地图的SDK研发工作.在技术和开发上肯定是亲临第一线的高手. 我们整理了游东先生的演讲,希望给广大开发者提供实实在在的帮助. 一.百度地图介绍:高端手机实现陀螺仪导航 我们可以看到百度这一块对SDK重视还是比较大,我们的迭代版本速度也是比较快.一般来说一个小版本是一个月左右,如果大版本升级可能三个月左右的时间.

【云图】如何制作东莞酒店地图?

原文:[云图]如何制作东莞酒店地图? 摘要:今天到深圳参加第二届电博会,果然不像车展或者漫展那样,会有萌妹纸,大家都好素净.晚上去东莞玩一圈,发现订不到酒店啊!各种商业中心关闭啊.于是想,那自己制作一张东莞酒店地图玩玩吧.于是在咖啡厅开始写代码,顺便等别人把酒店定好……啊,我果然是程序猿的命麽?!嗯,回到主题,制作好酒店地图,需要增加功能,就是按照星级,或者行政区进行分类查询检索.而且,还可以在云图上任意增减数据.真是出门在外居家旅行必备佳品,哈哈. ----------------------

百度地图API实现批量地址解析

1.前言 写这篇文章的原因是最近做一个GIS项目在网上爬取了一些数据,无奈只有地址的文字信息没有坐标信息,如何把信息显现在地图上呢?很纠结啊,查看了一下百度地图API惊奇的发现百度提供了地址解析的API,然后查看了他的Demo后豁然开朗,所以动手将自己的文字信息数据进行解析坐标信息.下面开始讲解. 2.方案 (1)自己数据库中的数据 (2)百度地图API Demo <!DOCTYPE html> <html> <head> <meta http-equiv=&qu

【API】高德地图API JS实现获取坐标和回显点标记

1.搜索+选择+获取经纬度和详细地址 2.回显数据并点标记 3.实现 第一步:引入资源文件 <!--引入高德地图JSAPI --><script src="//webapi.amap.com/maps?v=1.3&key=在官网申请一个key"></script><!--引入UI组件库(1.0版本) --><script src="//webapi.amap.com/ui/1.0/main.js">

js中实现高德地图坐标经纬度转百度地图坐标

1 function tobdMap(x, y) { 2 var x_pi = 3.14159265358979324 * 3000.0 / 180.0; 3 var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi); 4 var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi); 5 var bd_lon = z * Math.cos(theta) + 0.00

DEDE5.7如何制作网站地图?

DEDE用的人很多,可能大家在使用的过程中会碰到一些问 题,这很正常的,今天我们来讲讲DEDE5.7如何制作网站地图,其实网站地图分两种,一种做给网友看的,方便网友可以方便地找到自己想浏览的内容,另外 一种是做给搜索引擎蜘蛛看,方便蜘蛛在你网站上面抓取内容.    当然,我们这里讲的主要是针对蜘蛛的,因为DEDE默认的就有针对用户的网站地图,主要是以栏目的形式展现,这个可以在DEDE后台自行生成.其实大家印象当中的网站地图是XML格式的,一般命名成sitemap.xml,接下来进入正题.    

baidu地图:实现多点连线渲染

<script type="text/javascript"> var points = [ {"Lng":120.17787645967861,"Lat":30.251826748722667}, {"Lng":120.17786646842835,"Lat":30.251826580357911} ]; </script> <!DOCTYPE html> <ht