iOS 获取当点位置,并绘制当…

该实现代码包括三个类:MapController、Place、PlaceMark.直接调用mapcontroller类传入目的地坐标;

 

 #import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>    //这里要添加框架

@interface coreLocationViewController : UIViewController <CLLocationManagerDelegate>{
CLLocationManager *man;
}
@property(nonatomic, retain) CLLocationManager *man;

@end

#import "coreLocationViewController.h"
#import <CoreLocation/CoreLocation.h>

@implementation coreLocationViewController
@synthesize man;


- (void)viewDidLoad {
[super viewDidLoad];
man = [[CLLocationManager alloc] init];
// 如果可以利用本地服务时
if([man locationServicesEnabled]){
// 接收事件的实例
man.delegate = self;
// 发生事件的的最小距离间隔(缺省是不指定)
man.distanceFilter = kCLDistanceFilterNone;
// 精度 (缺省是Best)
man.desiredAccuracy = kCLLocationAccuracyBest;
// 开始测量
[man startUpdatingLocation];
}

}

// 如果GPS测量成果以下的函数被调用
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation{

// 取得经纬度
CLLocationCoordinate2D coordinate = newLocation.coordinate;
CLLocationDegrees latitude = coordinate.latitude;
CLLocationDegrees longitude = coordinate.longitude;
// 取得精度
CLLocationAccuracy horizontal = newLocation.horizontalAccuracy;
CLLocationAccuracy vertical = newLocation.verticalAccuracy;
// 取得高度
CLLocationDistance altitude = newLocation.altitude;
// 取得时刻
NSDate *timestamp = [newLocation timestamp];

// 以下面的格式输出 format: <latitude>, <longitude>> +/- <accuracy>m @ <date-time>
NSLog([newLocation description]);

// 与上次测量地点的间隔距离
if(oldLocation != nil){
CLLocationDistance d = [newLocation getDistanceFrom:oldLocation];
NSLog([NSString stringWithFormat:@"%f", d]);
}
}

// 如果GPS测量失败了,下面的函数被调用
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error{
NSLog([error localizedDescription]);
}


自己的代码:

#import <UIKit/UIKit.h>

#import <CoreLocation/CoreLocation.h>

#import<CoreLocation/CLLocation.h>

#import <MapKit/MapKit.h>

#import "ASIHTTPRequest.h"

#import "Place.h"

#import "PlaceMark.h"

//#import "RegexKitLite.h"

@interface MapViewController : UIViewController<CLLocationManagerDelegate,MKMapViewDelegate>{

    MKMapView *map;

    CLLocationManager *locManager;

    CLLocationCoordinate2D loc;

    UIImageView *_route_view;

    //采集的数据,主要是从google地图中得到路线的路标

    NSArray *_routes;

    //线路使用的颜色

    UIColor *_line_color;

    //http访问协议

    ASIHTTPRequest *_request;

    //其他的与地域管理有关的类

    MKReverseGeocoder *_geo;

    MKPointAnnotation *_pointAnnotation;

    MKPolyline* _routelay;

    CGFloat latitude;

    CGFloat longitude;

    

}

@property (nonatomic, retain) MKMapView *map;

@property (nonatomic, retain) CLLocationManager *locManager;

@property(nonatomic,retain)ASIHTTPRequest *request;

@property(nonatomic,retain)NSArray *routes;

@property(nonatomic,retain)UIImageView *route_view;

@property(nonatomic,retain)UIColor *line_color;

@property(nonatomic,retain)MKPolyline* routelay;

@property(assign)CGFloat latitude;

@property(assign)CGFloat longitude;


-(void) showRouteFrom: (Place*) f to:(Place*) t ;

@end


MapViewController.h类:

 

#import "MapViewController.h"

#import "SBJson.h"


@interface MapViewController(PrivateMethod)

-(NSMutableArray *)decodePolyLine: (NSMutableString *)encoded;

-(NSArray*) calculateRoutesFrom:(CLLocationCoordinate2D) f to: (CLLocationCoordinate2D) t ;

-(void) updateRouteView ;

-(void) centerMap;

@end


@implementation MapViewController

@synthesize map;

@synthesize locManager;

@synthesize request=_request;

@synthesize routes=_routes;

@synthesize route_view=_route_view;

@synthesize line_color=_line_color;

@synthesize routelay =  _routelay;

@synthesize longitude;

@synthesize latitude;



- (void)viewDidLoad {

    [super viewDidLoad];

    self.navigationItem.title = @"Google地图";

    map = [[MKMapView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 411.0f)];

    map.delegate = self;

    map.showsUserLocation = YES;

    [self.view addSubview:map];

    

    _route_view=[[UIImageView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 411.0f)];

    _route_view.userInteractionEnabled = NO;

    [map addSubview:_route_view];

    

    locManager = [[CLLocationManager alloc] init];

    locManager.delegate = self;

    locManager.desiredAccuracy = kCLLocationAccuracyBest;

    locManager.distanceFilter = 10.0f;

    [locManager startUpdatingLocation];

    

    self.line_color = [UIColor redColor];

    

    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];

[backButton setBackgroundImage:[UIImage imageNamed:@"naviback.png"] 

  forState:UIControlStateNormal];

[backButton setTitle:@" 返回" forState:UIControlStateNormal];

backButton.titleLabel.font = [UIFont systemFontOfSize:13];

[backButton addTarget:self action:@selector(navigationButtonPressed) 

forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];

[backButton release];

self.navigationItem.leftBarButtonItem = backItem;

[backItem release];

}


-(void)navigationButtonPressed{

    [self.navigationController popViewControllerAnimated:YES];

}


-(void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

    loc = [[locManager location]coordinate];

    MKCoordinateSpan span;

//设置精度,越小越精确

    span.latitudeDelta=0.01; //zoom level

    span.longitudeDelta=0.01; //zoom level

    

    MKCoordinateRegion region;

    region.span=span;

    region.center=loc;

    [map setRegion:region];

}


- (void)dealloc {

    [map release];

    [locManager release];

    [super dealloc];

}

#pragma mark -

#pragma mark Core Location Delegate Methods

- (void)locationManager:(CLLocationManager *)manager

    didUpdateToLocation:(CLLocation *)newLocation

           fromLocation:(CLLocation *)oldLocation {

//    NSLog(@"---------------");

//    NSLog(@"********newlocation is *%@",newLocation);

//    NSLog(@"********oldlocation is *%@",oldLocation);

    

    loc = [[locManager location]coordinate];

    Place* p1 = [[[Place alloc] init] autorelease];

    p1.latitude = loc.latitude;

    p1.longitude = loc.longitude;

    

    Place* p2 = [[[Place alloc] init] autorelease];

    p2.latitude = self.latitude;

    p2.longitude = self.longitude;

    

    [self showRouteFrom:p1 to:p2];

}


    //显示两点之间的线路

-(void) showRouteFrom: (Place*) f to:(Place*) t {

 

if(_routes) {

[map removeAnnotations:[map annotations]];

[_routes release];

}

 

PlaceMark* from = [[[PlaceMark alloc] initWithPlace:f] autorelease];

PlaceMark* to = [[[PlaceMark alloc] initWithPlace:t] autorelease];

 

[map addAnnotation:from];

[map addAnnotation:to];

 

        //计算出两点之间的线路所包含的点的数组

_routes = [[self calculateRoutesFrom:from.coordinate to:to.coordinate] retain];

        //根据数组画线

[self updateRouteView];

        //根据线路确定呈现范围

// [self centerMap];

}


-(NSArray*) calculateRoutesFrom:(CLLocationCoordinate2D) f to: (CLLocationCoordinate2D) t {

NSString* saddr = [NSString stringWithFormat:@"%f,%f", f.latitude, f.longitude];

    NSString* daddr = [NSString stringWithFormat:@"%f,%f", t.latitude, t.longitude];

        //    NSString* daddr = [NSString stringWithFormat:@"%f,%f",36.278292,140.737820];

    

    NSString* apiUrlStr = [NSString stringWithFormat:@"http://maps.google.com/maps/api/directions/json?origin=%@&destination=%@&sensor=true", saddr, daddr];

    NSURL* apiurl = [NSURL URLWithString:apiUrlStr];

    

    [self setRequest:[ASIHTTPRequest requestWithURL:apiurl]];

    [_request startSynchronous]; 

    NSString* apiResponse=[_request responseString];

    NSLog(@"temp is %@",apiResponse);

    NSDictionary *dic_data=[apiResponse JSONValue];

    NSArray *dic_routes =[dic_data objectForKey:@"routes"];

    

    NSDictionary *legs=[dic_routes objectAtIndex:0];

    

    NSDictionary *temp =[legs objectForKey:@"overview_polyline"];

    NSLog(@"temp is %@",temp);

    NSString *end_points=[temp objectForKey:@"points"];

    return [[self decodePolyLine:[end_points mutableCopy]]retain];

}



-(NSMutableArray *)decodePolyLine: (NSMutableString *)encoded {

[encoded replaceOccurrencesOfString:@"\" withString:@""

options:NSLiteralSearch

  range:NSMakeRange(0, [encoded length])];

NSInteger len = [encoded length];

NSInteger index = 0;

NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];

NSInteger lat=0;

NSInteger lng=0;

while (index < len) {

NSInteger b;

NSInteger shift = 0;

NSInteger result = 0;

do {

b = [encoded characterAtIndex:index++] - 63;

result |= (b & 0x1f) << shift;

shift += 5;

} while (b >= 0x20);

NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));

lat += dlat;

shift = 0;

result = 0;

do {

b = [encoded characterAtIndex:index++] - 63;

result |= (b & 0x1f) << shift;

shift += 5;

} while (b >= 0x20);

NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));

lng += dlng;

NSNumber *latitude1 = [[[NSNumber alloc] initWithFloat:lat * 1e-5] autorelease];

NSNumber *longitude1 = [[[NSNumber alloc] initWithFloat:lng * 1e-5] autorelease];

printf("[%f,", [latitude1 doubleValue]);

printf("%f]", [longitude1 doubleValue]);

CLLocation *loc1 = [[[CLLocation alloc] initWithLatitude:[latitude1 floatValue] longitude:[longitude1 floatValue]] autorelease];

[array addObject:loc1];

}

 

return array;

}



    //routes数组的内容 确定region的呈现范围

-(void) centerMap {

MKCoordinateRegion region;

    

CLLocationDegrees maxLat = -90;

CLLocationDegrees maxLon = -180;

CLLocationDegrees minLat = 90;

CLLocationDegrees minLon = 180;

for(int idx = 0; idx < _routes.count; idx++)

        {

CLLocation* currentLocation = [_routes objectAtIndex:idx];

if(currentLocation.coordinate.latitude > maxLat)

maxLat = currentLocation.coordinate.latitude;

if(currentLocation.coordinate.latitude < minLat)

minLat = currentLocation.coordinate.latitude;

if(currentLocation.coordinate.longitude > maxLon)

maxLon = currentLocation.coordinate.longitude;

if(currentLocation.coordinate.longitude < minLon)

minLon = currentLocation.coordinate.longitude;

        }

region.center.latitude     = (maxLat + minLat) / 2;

region.center.longitude    = (maxLon + minLon) / 2;

region.span.latitudeDelta  = maxLat - minLat;

region.span.longitudeDelta = maxLon - minLon;

 

[map setRegion:region animated:YES];

}



    //routes数组的内容 画线

-(void) updateRouteView {

CGContextRef context = CGBitmapContextCreate(nil, 

  _route_view.frame.size.width, 

  _route_view.frame.size.height, 

  8, 

  4 * _route_view.frame.size.width,

  CGColorSpaceCreateDeviceRGB(),

  kCGImageAlphaPremultipliedLast);

 

CGContextSetStrokeColorWithColor(context, _line_color.CGColor);

CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);

CGContextSetLineWidth(context, 5.0);

 

for(int i = 0; i < _routes.count; i++) {

CLLocation* location = [_routes objectAtIndex:i];

CGPoint point = [map convertCoordinate:location.coordinate toPointToView:_route_view];

 

if(i == 0) {

CGContextMoveToPoint(context, point.x, _route_view.frame.size.height - point.y);

} else {

CGContextAddLineToPoint(context, point.x, _route_view.frame.size.height - point.y);

}

}

 

CGContextStrokePath(context);

 

CGImageRef image = CGBitmapContextCreateImage(context);

UIImage* img = [UIImage imageWithCGImage:image];

 

_route_view.image = img;

CGContextRelease(context);

    

}


#pragma mark mapView delegate functions

- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated

{

_route_view.hidden = YES;

}


- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated

{

[self updateRouteView];

_route_view.hidden = NO;

[_route_view setNeedsDisplay];

}


@end


 

//

//  Place.h

//  Miller

//

//  Created by kadir pekel on 2/6/10.

//  Copyright 2010 __MyCompanyName__. All rights reserved.

//


#import <Foundation/Foundation.h>



@interface Place : NSObject {


NSString* name;

NSString* description;

double latitude;

double longitude;

}


@property (nonatomic, retain) NSString* name;

@property (nonatomic, retain) NSString* description;

@property (nonatomic) double latitude;

@property (nonatomic) double longitude;


@end


//

//  Place.m

//  Miller

//

//  Created by kadir pekel on 2/6/10.

//  Copyright 2010 __MyCompanyName__. All rights reserved.

//


#import "Place.h"



@implementation Place


@synthesize name;

@synthesize description;

@synthesize latitude;

@synthesize longitude;


- (void) dealloc

{

[name release];

[description release];

[super dealloc];

}


@end

 

//

//  PlaceMark.h

//  Miller

//

//  Created by kadir pekel on 2/7/10.

//  Copyright 2010 __MyCompanyName__. All rights reserved.

//


#import <Foundation/Foundation.h>

#import <MapKit/MapKit.h>

#import "Place.h"


@interface PlaceMark : NSObject <MKAnnotation> {


CLLocationCoordinate2D coordinate;

Place* place;

}


@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;

@property (nonatomic, retain) Place* place;


-(id) initWithPlace: (Place*) p;


@end


 

//

//  PlaceMark.m

//  Miller

//

//  Created by kadir pekel on 2/7/10.

//  Copyright 2010 __MyCompanyName__. All rights reserved.

//


import "PlaceMark.h"



@implementation PlaceMark


@synthesize coordinate;

@synthesize place;


-(id) initWithPlace: (Place*) p

{

self = [super init];

if (self != nil) {

coordinate.latitude = p.latitude;

coordinate.longitude = p.longitude;

self.place = p;

}

return self;

}


- (NSString *)subtitle

{

return self.place.description;

}

- (NSString *)title

{

return self.place.name;

}


- (void) dealloc

{

[place release];

[super dealloc];

}



@end#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值