如何根据最近的引脚设置地图缩放到当前位置

时间:2012-11-26 21:12:10

标签: iphone ios

现在我根据用户当前位置设置我的区域。我现在想设置缩放级别,这样我就可以看到用户的当前位置以及通过json拉入的最近的引脚。

直到运行时间,应用程序才知道引脚数或所述引脚的位置。

这是我到目前为止所拥有的。

@implementation LocationsViewController

@synthesize mapView;
@synthesize locationManager;
@synthesize phone;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) 
    {
        self.title = NSLocalizedString(@"Locations", @"Locations");
        self.tabBarItem.image = [UIImage imageNamed:@"locations"];
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

 #pragma mark - View lifecycle

 //Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad
{
    [super viewDidLoad];
    self.locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"New latitude: %f", newLocation.coordinate.latitude);
    NSLog(@"New longitude: %f", newLocation.coordinate.longitude);

    MKCoordinateRegion region;
    region.center.latitude =newLocation.coordinate.latitude;
    region.center.longitude=  newLocation.coordinate.longitude;
    region.span.longitudeDelta=0.2;
    region.span.latitudeDelta =0.2;
    [mapView setRegion:region animated:YES];
    [mapView setDelegate:self];
    //[locationManager stopUpdatingLocation];

}

-(void)viewDidDisappear:(BOOL)animated
{
    [locationManager stopUpdatingLocation];   
}

-(void)viewDidAppear:(BOOL)animated 
{
    [super viewDidAppear:animated];

    [locationManager startUpdatingLocation];

    if([self connectedToNetwork] != YES)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"OH NO!" message:@"To get the latest information you need a data or wi-fi connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
    else
    {
        [mapView removeAnnotations:mapView.annotations];

        NSString *urlString = [NSString stringWithFormat:@"http://www.mywebsite.com/json.json"];

        NSURL *url = [NSURL URLWithString:urlString];

        NSData *data = [NSData dataWithContentsOfURL:url];

        NSError *error;

        NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

        for(id key in json) {
            id value = [json objectForKey:key];
            NSString *titlePin = [value valueForKey:@"address"];
            NSString *address = [value valueForKey:@"title"];
            NSString *latitude = [value valueForKey:@"latitude"];
            NSString *longitude = [value valueForKey:@"longitude"];

            NSArray* foo = [address componentsSeparatedByString: @":"];
            NSString* address2 = [foo objectAtIndex: 0];
            phone = [foo objectAtIndex: 1];

            double myLatitude = [latitude doubleValue];
            double myLongitude = [longitude doubleValue];

            MKCoordinateRegion location1;
            location1.center.latitude =myLatitude;
            location1.center.longitude= myLongitude;
            location1.span.longitudeDelta=0.1;
            location1.span.latitudeDelta =0.1;

            MapAnnotation *ann1 =[[[MapAnnotation alloc] init] autorelease];
            ann1.title=[NSString stringWithFormat:@"%@",titlePin];
            ann1.subtitle=[NSString stringWithFormat:@"%@",address2];
            ann1.phone=[NSString stringWithFormat:@"%@",phone];
            ann1.coordinate= location1.center;
            [mapView addAnnotation:ann1];
            [phone retain];

        }
     }
}

-(MKAnnotationView *) mapView:(MKMapView *)mapView2 viewForAnnotation:(id<MKAnnotation>)annotation {
    if (annotation == mapView2.userLocation) {
        return nil;
    }else{
         MKPinAnnotationView *MyPin=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"current"];
        MyPin.pinColor = MKPinAnnotationColorPurple;

        UIButton *advertButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
         [advertButton setImage:[UIImage imageNamed:@"mapphone"] forState:UIControlStateNormal];
         [advertButton addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
         MyPin.rightCalloutAccessoryView = advertButton;


        MyPin.draggable = NO;
        MyPin.highlighted = YES;
        MyPin.animatesDrop=TRUE;
        MyPin.canShowCallout = YES;

        return MyPin;
     }
 }

 -(void)button:(id)sender {

     UIButton *button = (UIButton *)sender;

     MKPinAnnotationView *annotationView = (MKPinAnnotationView*)button.superview.superview;

     MapAnnotation *mapAnnotation = annotationView.annotation;

     UIDevice *device = [UIDevice currentDevice];
     if ([[device model] isEqualToString:@"iPhone"] ) {
         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",mapAnnotation.phone]]];
     } else {
         UIAlertView *Notpermitted=[[UIAlertView alloc] initWithTitle:mapAnnotation.phone message:@"Your device doesn't support this feature." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
         [Notpermitted show];
         [Notpermitted release];
    }

}

 - (BOOL) connectedToNetwork
 {  
    Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus internetStatus = [r currentReachabilityStatus];
    BOOL internet;
    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
        internet = NO;
    } else {
        internet = YES;
    }
    return internet;
} 

- (void)viewDidUnload
{
    [super viewDidUnload];
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
}

@end

1 个答案:

答案 0 :(得分:0)

我做了类似的事情,但基于两个注释,而不是用户的位置。您应该能够使用mapView.userLocation.coordinate替换mapView.centerCoordinate。

在viewForAnnotation中

   CLLocation *centerLoc = [[CLLocation alloc] initWithLatitude:mapView.centerCoordinate.latitude longitude:mapView.centerCoordinate.longitude];
   CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:[annotation coordinate].latitude longitude:[annotation coordinate].longitude];
   CLLocationDistance distance = [loc2 distanceFromLocation:centerLoc];

   MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(mapView.centerCoordinate, distance*2, distance*2);
   MKCoordinateRegion adjustedRegion = [mapView regionThatFits:viewRegion];
   [mapView setRegion:adjustedRegion animated:YES];

注意,每次添加注释时,此代码都会重新计算缩放级别。您可能需要保存距离,并且只有在新距离大于先前距离时才更改地图。