1

現在、ユーザーの現在の場所に基づいて地域を設定しています。ズームレベルを設定して、ユーザーの現在の場所と、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
4

1 に答える 1

0

私は似たようなことをしましたが、ユーザーの場所ではなく、2 つの注釈に基づいていました。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];

このコードは、注釈を追加するたびにズーム レベルを再計算することに注意してください。距離を保存し、新しい距離が以前の距離よりも大きい場合にのみマップを変更する必要がある場合があります。

于 2012-11-27T05:00:07.873 に答える