.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
@interface SecondViewController : UIViewController<CLLocationManagerDelegate,MKMapViewDelegate,NSURLConnectionDataDelegate,NSURLConnectionDelegate>
{
IBOutlet UIView *mapBottomView;
IBOutlet UITextView *locationTextView;
CLLocationManager *locationManager;
MKMapView *mapShowView;
}
- (IBAction)showMapView:(id)sender;
- (IBAction)reverseGeocoder:(id)sender;
@end
==================================================================================
.m
//
// SecondViewController.m
// Map_Location
//
// Created by yhy on 13-1-30.
// Copyright (c) 2013年 yhy. All rights reserved.
//
#import "SecondViewController.h"
#import "MapAnnotation.h"
#define GoogleMapBaseApi @"https://maps.googleapis.com/maps/api"
@interface SecondViewController ()
@end
@implementation SecondViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = 5.0f;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
mapShowView = [[MKMapView alloc] initWithFrame:mapBottomView.bounds];
//顯示用戶位置
mapShowView.showsUserLocation = YES;
// mapShowView.mapType = MKMapTypeHybrid;
//是否可滑動
mapShowView.scrollEnabled = YES;
//是否可放大縮小
mapShowView.zoomEnabled = YES;
mapShowView.delegate = self;
[mapBottomView addSubview:mapShowView];
//藍鷗坐標
// latitude = 40.03424
// longitude = 116.317856
// CLLocationDegrees latitude = [@"40.03424" doubleValue];
// CLLocationDegrees longitude = [@"116.317856" doubleValue];
// CLLocation * showLocation = [[CLLocation alloc] initWithLatitude:latitude
// longitude:longitude];
// //根據經緯度范圍顯示
// mapShowView.region = MKCoordinateRegionMake(showLocation.coordinate, MKCoordinateSpanMake(0.0045f, 0.0045f));
// //根據距離范圍顯示
//// mapShowView.region = MKCoordinateRegionMakeWithDistance(showLocation.coordinate, 500, 500);
//
// mapShowView.showsUserLocation = YES;
// mapShowView.mapType = MKMapTypeHybrid;
// mapShowView.scrollEnabled = YES;
// mapShowView.zoomEnabled = YES;
// mapShowView.delegate = self;
// [mapShowView release];
}
- (IBAction)showMapView:(id)sender
{
[locationManager startUpdatingLocation];
}
- (IBAction)reverseGeocoder:(id)sender
{
[self getReverseGeocoderInfo];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * getTouch = [touches anyObject];
//屏幕上當前點擊位置的坐標
CGPoint touchPoint = [getTouch locationInView:mapShowView];
//將屏幕上的點轉換成地圖上的點
CLLocationCoordinate2D location = [mapShowView convertPoint:touchPoint
toCoordinateFromView:mapShowView];
//
locationTextView.text = [NSString stringWithFormat:@"latitude = %f\nlongitude = %f",location.latitude,location.longitude];
}
//定位成功后執行這個代理
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
{
//美國蘋果總部坐標
// latitude = 37.785834
// longitude = -122.406417
//藍鷗坐標
// latitude = 40.03424
// longitude = 116.317856
//上地地鐵坐標
// latitude = 40.03316
// longitude = 116.319738
//上地華聯坐標
// latitude = 40.02874
// longitude = 116.312919
if (locations.count)
{
CLLocation * location = (CLLocation *)[locations objectAtIndex:0];
NSLog(@"latitude = %f",location.coordinate.latitude);
NSLog(@"longitude = %f",location.coordinate.longitude);
//根據經緯度范圍顯示
mapShowView.region = MKCoordinateRegionMake(location.coordinate, MKCoordinateSpanMake(0.0045f, 0.0045f));
//根據距離范圍顯示
mapShowView.region = MKCoordinateRegionMakeWithDistance(location.coordinate, 1000, 1000);
}
[locationManager stopUpdatingLocation];
}
//獲取經緯度失敗時候調用的代理方法
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
NSLog(@"error = %@",error);
}
#pragma mark -------------------------
#pragma mark 范圍改變
//移動、縮放地圖
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
NSLog(@"mapView region Will ChangeAnimated");
}
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
NSLog(@"mapView region Did ChangeAnimated");
}
#pragma mark -------------------------
#pragma mark 地圖加載
//移動、縮放地圖重新開始加載地圖
//mapView將要開始加載地圖時候調用的代理
- (void)mapViewWillStartLoadingMap:(MKMapView *)mapView
{
NSLog(@"mapView Will Start Loading Map");
}
//mapView加載完地圖時調用的方法
- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView
{
NSLog(@"mapView Did Finish Loading Map");
//自定義注釋(起始點)
MapAnnotation * lanouAnnotation = [[MapAnnotation alloc] initWithCoordinate:CLLocationCoordinate2DMake([@"40.03424" doubleValue], [@"116.317856" doubleValue])];
lanouAnnotation.title = @"藍鷗科技";
lanouAnnotation.subtitle = @"北京市海淀區上地信息路上地佳園";
//自定義注釋(結束點)
MapAnnotation * shangdiAnnotation = [[MapAnnotation alloc] initWithCoordinate:CLLocationCoordinate2DMake([@"40.03316" doubleValue], [@"116.319738" doubleValue])];
shangdiAnnotation.title = @"上地地鐵站";
shangdiAnnotation.subtitle = @"北京市海淀區上地信息路";
//單個添加
[mapView addAnnotation:lanouAnnotation];
[mapView addAnnotation:shangdiAnnotation];
// //一起添加
// NSArray * annotations = [NSArray arrayWithObjects:lanouAnnotation,shangdiAnnotation, nil];
// [mapView addAnnotations:annotations];
[lanouAnnotation release];
[shangdiAnnotation release];
}
- (void)mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error
{
}
#pragma mark -------------------------
#pragma mark 注解視圖
//- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
//{
// for (MKPinAnnotationView * mkaView in views){
// MapAnnotation * annotation = (MapAnnotation *)mkaView.annotation;
//
// if ([annotation.title isEqualToString:@"藍鷗科技"]) {
// mkaView.pinColor = MKPinAnnotationColorGreen;
// }
//
// if ([annotation.title isEqualToString:@"上地地鐵站"]) {
// mkaView.pinColor = MKPinAnnotationColorRed;
//
// UIButton * rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
// [rightButton addTarget:self
// action:@selector(showDetailInMapClient)
// forControlEvents:UIControlEventTouchUpInside];
//
// mkaView.rightCalloutAccessoryView = rightButton;
// }
//
// }
//}
//自定義注釋view
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]]) {
return nil;
}
if ([annotation isKindOfClass:[MapAnnotation class]]) {
static NSString * annotationIdentifier = @"annotation identifier";
MKPinAnnotationView * pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationIdentifier];
if (!pinView) {
MKPinAnnotationView *annotationView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationIdentifier] autorelease];
annotationView.image = [UIImage imageNamed:@"pin.png"];
annotationView.canShowCallout = YES;
UIButton * rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self
action:@selector(showDetailInMapClient)
forControlEvents:UIControlEventTouchUpInside];
annotationView.rightCalloutAccessoryView = rightButton;
return annotationView;
}else{
pinView.annotation = annotation;
return pinView;
}
}
return nil;
}
- (void)showDetailInMapClient
{
//藍鷗到北京體育大學的路線
UIDevice * device = [UIDevice currentDevice];
if ([device.systemVersion floatValue] < 6.0) {
NSString * myLoc = [NSString stringWithFormat:@"%f,%f",[@"40.03424" doubleValue],[@"116.317856" doubleValue]];
NSString * otherLoc =[NSString stringWithFormat:@"%f,%f",[@"39.987873" doubleValue],[@"116.305726" doubleValue]];
NSString * url = [NSString stringWithFormat:@"http://maps.google.com/?saddr=%@&daddr=%@&dirflg=t",[myLoc stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[otherLoc stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}else{
CLLocationCoordinate2D from = CLLocationCoordinate2DMake([@"40.03424" doubleValue],[@"116.317856" doubleValue]);
MKPlacemark * fromMark = [[[MKPlacemark alloc] initWithCoordinate:from
addressDictionary:nil] autorelease];
MKMapItem * fromLocation = [[MKMapItem alloc] initWithPlacemark:fromMark];
fromLocation.name = @"藍鷗科技";
fromLocation.phoneNumber = @"123456789";
fromLocation.url = [NSURL URLWithString:@"www.lanou3g.com"];
CLLocationCoordinate2D to = CLLocationCoordinate2DMake([@"39.987873" doubleValue],[@"116.305726" doubleValue]);
MKPlacemark * toMark = [[[MKPlacemark alloc] initWithCoordinate:to
addressDictionary:nil] autorelease];
MKMapItem * toLocation = [[MKMapItem alloc] initWithPlacemark:toMark];
toLocation.name = @"北京體育大學";
NSArray * values = [NSArray arrayWithObjects:
MKLaunchOptionsDirectionsModeDriving,
[NSNumber numberWithBool:YES],
[NSNumber numberWithInt:2],
nil];
NSArray * keys = [NSArray arrayWithObjects:
MKLaunchOptionsDirectionsModeKey,
MKLaunchOptionsShowsTrafficKey,
MKLaunchOptionsMapTypeKey,nil];
[MKMapItem openMapsWithItems:[NSArray arrayWithObjects:fromLocation, toLocation, nil]
launchOptions:[NSDictionary dictionaryWithObjects:values
forKeys:keys]];
[fromLocation release];
[toLocation release];
}
}
#pragma mark -------------------------
#pragma mark 逆向地理編碼
- (void)getReverseGeocoderInfo
{
NSString * baseUrl = [NSString stringWithFormat:@"%@/geocode/json?latlng=%@,%@&sensor=true&language=zh-CN",GoogleMapBaseApi,@"39.987873",@"116.305726"];
NSLog(@"reverse = %@",baseUrl);
// https://maps.googleapis.com/maps/api/geocode/json?latlng=40.03424,116.317856&sensor=true&language=zh-CN
}
#pragma mark -------------------------
#pragma mark 定位用戶location
//獲取用戶當前地理位置后的代理
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
NSLog(@"mapView did Update User Location");
mapView.userLocation.title = @"藍鷗科技";
mapView.userLocation.subtitle = [NSString stringWithFormat:@"lat = %f,lon = %f",userLocation.coordinate.latitude,userLocation.coordinate.longitude];
}
- (void)mapView:(MKMapView *)mapView didFailToLocateUserWithError:(NSError *)error
{
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
[mapBottomView release];
[mapShowView release];
[locationTextView release];
[super dealloc];
}
- (void)viewDidUnload {
[mapBottomView release];
mapBottomView = nil;
[locationTextView release];
locationTextView = nil;
[super viewDidUnload];
}
@end
====================================================================================