如何获得地图和缩放到用户位置的权限?

时间:2015-10-13 12:45:05

标签: ios objective-c mapkit mkannotation mkannotationview

我厌倦了获取自定义注释的indexpath, 我使用此代码获取我的indexpath

 NSUInteger index =[mapView.annotations indexOfObject:view.annotation];

它没有真正起作用,因为在我的地图中,我得到了正确的lat和lang但没有获得pinview的真实数据

pusingpalagw是我的子类 这是我的代码:

-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{

 // [(UIImageView *)view.leftCalloutAccessoryView setImageWithURL:[NSURL URLWithString:self.content.MERCHANT_IMAGE] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
//if ([view.annotation isKindOfClass:[pusingpalagw class]]) {
  //  pusingpalagw *annot = view.annotation;
    //NSInteger index = [self.arrayOfAnnotations indexOfObject:annot];
  NSUInteger index =[mapView.annotations indexOfObject:view.annotation];
 if (!self.content) {
    pusingpalagw *calloutView = [[pusingpalagw alloc] initWithFrame:CGRectMake(0.0, 0.0, 242.0, 57.0)];
    self.content12 = [self.listContent objectAtIndex:index];
    calloutView.titleLabel.text = self.content12.MERCHANT_NAME;
    calloutView.subtitleLabel.text = self.content12.MERCHANT_NAME;
    //UIView *rating2 = (UIView*)[cell2 viewWithTag:110];
    _starRating = [[EDStarRating alloc]initWithFrame:CGRectMake(calloutView.viewRating.frame.origin.x-15, calloutView.viewRating.frame.origin.y,80,20)];
    _starRating.backgroundColor  = [UIColor clearColor];
    self.starRating.starImage = [UIImage imageNamed:@"kuningstarkosong"];
    self.starRating.starHighlightedImage = [UIImage imageNamed:@"kuningstarfull"] ;
    _starRating.maxRating = 5.0;
    _starRating.delegate = self;
    _starRating.horizontalMargin = 15.0;
    _starRating.editable=NO;
    _starRating.rating= [self.content12.MERCHANT_RATTING floatValue];
    _starRating.displayMode=EDStarRatingDisplayHalf;
    [_starRating  setNeedsDisplay];
    [calloutView.viewRating addSubview:_starRating];
    NSLog(@"keluarbintang%@",_starRating);
    NSURL *url = [NSURL URLWithString:self.content12.MERCHANT_IMAGE];
    NSData *imageData = [NSData dataWithContentsOfURL:url];
    UIImage *abs = [UIImage imageWithData:imageData];
    [calloutView.imageMap setImage:abs];
    //[calloutView.buttonDetail setTitle: @"Post" forState: UIControlStateNormal];
    UIButton *buttonAja = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, calloutView.frame.size.width, calloutView.frame.size.height)];
    [buttonAja setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //[buttonAja setTitle: @"Post" forState: UIControlStateNormal];
    buttonAja.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [buttonAja addTarget:self action:@selector(goDetail:) forControlEvents:UIControlEventTouchUpInside];
    [calloutView addSubview:buttonAja];

    calloutView.center = CGPointMake(CGRectGetWidth(view.bounds) / 2.0, 0.0);
    [view addSubview:calloutView];
} 

2 个答案:

答案 0 :(得分:0)

//获得许可

if([CLLocationManager locationServicesEnabled]){

           NSLog(@"Location Services Enabled");

           if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied){
                alert = [[UIAlertView alloc] initWithTitle:@"App Permission Denied" 
                                                        message:@"To re-enable, please go to Settings and turn on Location Service for this app." 
                                                       delegate:nil 
                                              cancelButtonTitle:@"OK" 
                                              otherButtonTitles:nil];
                [alert show];
            }
        }

//设置用户位置

  - (void)viewDidLoad
 {
    [super viewDidLoad];
    self.mapView.showsUserLocation=YES;
    self.mapView.delegate = self;
    [self.mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
 }

...

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation 
{
    MKCoordinateRegion mapRegion;   
    mapRegion.center = mapView.userLocation.coordinate;
    mapRegion.span.latitudeDelta = 0.2;
    mapRegion.span.longitudeDelta = 0.2;

    [mapView setRegion:mapRegion animated: YES];
}

答案 1 :(得分:0)

IOS 8或更高版本的许可: -

#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)


if ([CLLocationManager locationServicesEnabled] )
{
    if (self.locationManager == nil )
    {
        self.locationManager.delegate = (id)self;
        self.locationManager = [[CLLocationManager alloc] init];
     #ifdef __IPHONE_8_0

        if(IS_OS_8_OR_LATER)
        {
               // Use one or the other, not both. Depending on what you put in info.plist
               [self.locationManager requestWhenInUseAuthorization];
               [self.locationManager requestAlwaysAuthorization];
        }
     #endif

        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = kDistanceFilter; //kCLDistanceFilterNone// kDistanceFilter;
    }

    [self.locationManager startUpdatingLocation];
    self.mapViewForPlace.showsUserLocation = YES;
    [self.locationManager setDelegate:self];

    NSLog(@"Location Title Is: %@", self.mapViewForPlace.userLocation.title);


}

添加info.plist NSLocationWhenInUseUsageDescription 字符串类型。

 -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
 {


 #ifdef __IPHONE_8_0

  if(IS_OS_8_OR_LATER) {
    // Use one or the other, not both. Depending on what you put in info.plist
     [self.locationManager requestWhenInUseAuthorization];
     [self.locationManager requestAlwaysAuthorization];
   }
#endif

 self.mapViewForPlace.showsUserLocation = YES;
 self.currentLocation = [locations lastObject];
 // here we get the current location

 NSLog(@"Current Locations : %@",self.currentLocation);
// CLLocation* location = (CLLocation*)locations.lastObject;
// Use Apple's Geocoder to figure the name of the place
CLGeocoder* geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:self.currentLocation completionHandler: ^(NSArray* placemarks, NSError* error) {
    if (error != nil) {
        NSLog(@"Error in geo coder: %@", error);
    }
    else {
        if (placemarks.count == 0) {
            NSLog(@"The address couldn't be found");
        }
        else {
            // Get nearby address
            CLPlacemark* placemark = placemarks[0];

            // Get the string address and store it
            NSString* locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
            //location.name = locatedAt;

            currentLocationNameIs=locatedAt;

             NSLog(@"The address is: %@", locatedAt);
         }
     }
   }];
 }


     - (void) locationManager:(CLLocationManager *) manager didUpdateToLocation:(CLLocation *) newLocation fromLocation:(CLLocation *) oldLocation
    {
    self.currentLocation = newLocation;
    self.mapViewForPlace.showsUserLocation = YES;
    NSLog(@"New location Cordinate : %f   %f",self.mapViewForPlace.userLocation.coordinate.latitude,self.mapViewForPlace.userLocation.coordinate.longitude);

   [self.locationManager stopUpdatingLocation];

   }




 - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation

   {
     // If it's the user location, just return nil.
     if ([annotation isKindOfClass:[MKUserLocation class]])
      return nil;

      // Handle any custom annotations.
      if ([annotation isKindOfClass:[MKPointAnnotation class]])
     {
      // Try to dequeue an existing pin view first.
      MKAnnotationView *pinView = (MKAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"CustomPinAnnotationView"];
    if (!pinView)
    {
        // If an existing pin view was not available, create one.
        pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomPinAnnotationView"];
        //pinView.animatesDrop = YES;
        pinView.canShowCallout = YES;
        pinView.image = [UIImage imageNamed:@"facebook30.png"];
        pinView.calloutOffset = CGPointMake(0, 32);

        // Add a detail disclosure button to the callout.
        UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        pinView.rightCalloutAccessoryView = rightButton;

        // Add an image to the left callout.
        UIImageView *iconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"facebook30.png"]];
        pinView.leftCalloutAccessoryView = iconView;

      } else {
        pinView.annotation = annotation;
     }
     return pinView;
  }
  return nil;
 }
相关问题