IOS 地图

一,获得当前地理信息

@interface ViewController : UIViewController<CLLocationManagerDelegate>
@property (nonatomic,strong)CLLocationManager *locationManager;
@property (nonatomic,strong)CLLocation *startingPoint;

@property (strong, nonatomic) IBOutlet UILabel *latitudeLabel;

@property (strong, nonatomic) IBOutlet UILabel *longitudeLabel;

@property (strong, nonatomic) IBOutlet UILabel *horizontalAccuracyLabel;

@property (strong, nonatomic) IBOutlet UILabel *VerticalAccuracyLabel;

@property (strong, nonatomic) IBOutlet UILabel *altitudeLabel;

@property (strong, nonatomic) IBOutlet UILabel *distanceTraveledLabel;
 
@end

二,实现代码

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.locationManager=[[CLLocationManager alloc]init];
    self.locationManager.desiredAccuracy=kCLLocationAccuracyHundredMeters;
    self.locationManager.delegate=self;
    [self.locationManager startUpdatingLocation];
    // Do any additional setup after loading the view, typically from a nib.
}
 
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    if (self.startingPoint==nil) {
        self.startingPoint=[locations lastObject];
    }
    self.latitudeLabel.text=[NSString stringWithFormat:@"%g",self.startingPoint.coordinate.latitude];
    self.longitudeLabel.text=[NSString stringWithFormat:@"%g",self.startingPoint.coordinate.longitude];
    self.horizontalAccuracyLabel.text=[NSString stringWithFormat:@"%gm",self.startingPoint.horizontalAccuracy];
    self.VerticalAccuracyLabel.text=[NSString stringWithFormat:@"%gm",self.startingPoint.verticalAccuracy];
    self.altitudeLabel.text=[NSString stringWithFormat:@"%gm",self.startingPoint.altitude];
    self.distanceTraveledLabel.text=[NSString stringWithFormat:@"%gm",[self.startingPoint distanceFromLocation:[locations lastObject]]];
    
}

三,地图的应用,创建自定义类MapAnnotation 重写三个属性

@interface MapAnnotation : NSObject<MKAnnotation>
@property (nonatomic)CLLocationCoordinate2D coordinate;
@property (nonatomic,  copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;

-(id)initWithCoordinate:(CLLocationCoordinate2D)aCoordinate;//init method
@end

-(id)initWithCoordinate:(CLLocationCoordinate2D)aCoordinate
{
    if (self=[super init]) {
        self.coordinate=aCoordinate;
    }
    return self;
}


四,实现类

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

@interface DetailViewController : UIViewController<CLLocationManagerDelegate,MKMapViewDelegate>
{
    MKMapView *_mapView;
}
@property (nonatomic,retain)CLLocationManager *locManager;
@property (nonatomic,retain)CLLocation *current;

@end

 //实现
#import "DetailViewController.h"
#import "MapAnnotation.h"

@interface DetailViewController ()
@property (nonatomic,strong)NSDictionary *jsonDic;
@end

@implementation DetailViewController



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
     
    }
    return self;
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    self.jsonDic=[NSDictionary dictionary];
   // [self.navigationController.navigationBar setHidden:YES];

     // self.view.backgroundColor=[UIColor redColor];
    self.navigationController.navigationBar.tintColor=[UIColor colorWithRed:0.20392f green:0.19607f blue:0.61176f alpha:1.0f];
    
    self.locManager=[[CLLocationManager alloc]init];
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"用户未开启定位服务");
        return;
    }
    //location service
    self.locManager.desiredAccuracy=kCLLocationAccuracyHundredMeters;
    self.locManager.distanceFilter=100;
    self.locManager.delegate=self;
    [self.locManager startUpdatingLocation];
   
    //mapView
    _mapView=[[MKMapView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    _mapView.backgroundColor=[UIColor redColor];
    _mapView.mapType=0;
    _mapView.userTrackingMode=MKUserTrackingModeFollow;
    self.view = _mapView;
  //  [self.view addSubview:mapView];
    _mapView.delegate=self;
    
}


//to get location update
//when CLLocation data successful, to invoke this method
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
//    //to set current location
    self.current=[locations lastObject];
//    //location map and user interaction
    _mapView.region=MKCoordinateRegionMake(self.current.coordinate, MKCoordinateSpanMake(0.02, 0.02));
    
    //reverse geocode
//      CLGeocoder *geocoder=[[CLGeocoder alloc] init];
//    [geocoder reverseGeocodeLocation:self.current completionHandler:^(NSArray *placemarks, NSError *error) {
//        CLPlacemark *placemark=[placemarks lastObject];
//        NSDictionary *dic=[placemark.addressDictionary objectForKey:@"SubLocality"];
//         NSLog(@"dic=%@",dic);
//    }];
//
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"%@ error=%@",@"access denyed",error.localizedDescription);
}

-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    MapAnnotation *annotation;//=[MapAnnotation alloc]initWithCoordinate:<#(CLLocationCoordinate2D)#>
    NSMutableArray *annotations=[NSMutableArray array];
    self.navigationItem.title=@"searching ....";
    //add current annotation
    if (self.current) {
        annotation=[[MapAnnotation alloc]initWithCoordinate:self.current.coordinate];
        annotation.title=@"您的当前位置";
        [annotations addObject:annotation];
    }
    //clear map
    [_mapView removeAnnotations:mapView.annotations];
    
    //interested place around you
    [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;//show networkActivity
    [self performSelector:@selector(setTitle:) withObject:@"关联外面" afterDelay:0.1f];
    
    //周边5000m内药店所搜
    NSString *urlstr=[NSString stringWithFormat:@"http://api.map.baidu.com/place/v2/search?&q=%%E8%%8D%%AF%%E5%%BA%%97&location=%f,%f&radius=5000&output=json&ak=NUF7e0S6EvXLmUZOcprRyoBq",self.current.coordinate.latitude,self.current.coordinate.longitude];
    NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:urlstr]];
   
    self.jsonDic=[NSJSONSerialization JSONObjectWithData:data options:0 error:Nil];
   
    //get array ,if null return
    if (((NSArray *)[self.jsonDic objectForKey:@"results"]).count==0) {
        return;
    }

    //to parse dic in the array
    for (NSDictionary *dics in [self.jsonDic objectForKey:@"results"]) {
        NSString *address=[dics objectForKey:@"address"];
        NSDictionary *location=[dics objectForKey:@"location"];
        NSString *name=[dics objectForKey:@"name"];
        
        CLLocationCoordinate2D coordinate;
        coordinate.latitude=[[location objectForKey:@"lat"] floatValue];
        coordinate.longitude=[[location objectForKey:@"lng"]floatValue];
        
        annotation=[[MapAnnotation alloc]initWithCoordinate:coordinate];
        annotation.title=name;
        annotation.subtitle=address;
        [annotations addObject:annotation];
    
//        NSLog(@"name=%@",name);
//        NSLog(@"address=%@",address);
      
          }
    //stop showing the network and add annotation to annotations
    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
    [mapView addAnnotations:annotations];
    
}

-(void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
//    NSLog(@"%@",views);
    for (MKPinAnnotationView *pinview in views) {
        if (![pinview isKindOfClass:[MKPinAnnotationView class]]) {
            continue;
        }
        NSLog(@"%@",pinview);
        if ([pinview.annotation.title isEqualToString:@"您的当前位置"] ) {
             pinview.pinColor=MKPinAnnotationColorPurple;
             pinview.rightCalloutAccessoryView=nil;
            continue;
        }
        //other annotation is red and have a button
        pinview.pinColor=MKPinAnnotationColorRed;
        UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
        pinview.rightCalloutAccessoryView=button;
    }
}

//to response annotation button click
-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    MapAnnotation *annotation=view.annotation;
   // [UIApplication sharedApplication]openURL:[NSURL URLWithString:annotation.subtitle];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

原文地址:https://www.cnblogs.com/huntaiji/p/3485086.html