繁体   English   中英

如何根据最近的图钉将地图缩放设置为当前位置

[英]How do I set map zoom based on nearest pin to current location

现在,我正在根据用户的当前位置设置地区。 我现在想设置缩放级别,以便可以看到用户的当前位置以及通过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

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

在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];

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM