Запрос текущего местоположения по событию клика - PullRequest
0 голосов
/ 24 октября 2011

Я показываю континент Австралия, когда запускается приложение Map.У меня есть одна кнопка, на которой я хочу установить кодировку для текущего местоположения и увеличить ее после нажатия кнопки.Я получаю текущую широту и долготу и могу перейти в URL веб-сервиса.Я сделал следующее кодирование

   - (void)viewDidLoad 
  { 

//to set the australia region
CLLocationCoordinate2D AusLoc = {-19.048230,133.685730};
MKCoordinateSpan AusSpan = MKCoordinateSpanMake(45, 45);
MKCoordinateRegion AusRegion = MKCoordinateRegionMake(AusLoc, AusSpan);

mapView.region = AusRegion;




    locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation]; }

и

   - (void)locationManager:(CLLocationManager *)manager
 didUpdateToLocation:(CLLocation *)newLocation
       fromLocation:(CLLocation *)oldLocation
  {

if((fabs(newLocation.coordinate.latitude) > 0.001) || (fabs(newLocation.coordinate.longitude) > 0.001)) {
    NSLog(@"Got location %f,%f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
    if (currentLocation != nil) {
        [currentLocation release];
    }
    currentLocation = newLocation;
    [currentLocation retain];
}
NSString *lati=[NSString stringWithFormat:@"%f", newLocation.coordinate.latitude];
NSString *longi=[NSString stringWithFormat:@"%f", newLocation.coordinate.longitude];

}

на кнопке поиска (вызов веб-службы)

NSString *url = [NSString stringWithFormat:@"http://.....url...../hespdirectory/phpsqlsearch_genxml.php?lat=%f&lng=%f&radius=%f",locationManager.location.coordinate.latitude,locationManager.location.coordinate.longitude,radius];

Обновлено с кодированием:

    - (IBAction) showAddress {

    if (locationManager.location == nil)
{
    NSLog(@"user location not found yet or service disabled/denied");
}
else
{



    // Change map region using span (degrees)...
    MKCoordinateSpan span = MKCoordinateSpanMake(0.001, 0.001);
    MKCoordinateRegion region = MKCoordinateRegionMake
    (locationManager.location.coordinate, span);
    [mapView setRegion:region animated:YES];
}

   }

Когда я устанавливаю mapView.showUserLocation = YES;он показывает текущее местоположение при запуске приложения карты до нажатия кнопки.Я запутался с предыдущим ответом.Итак, какой код я должен поместить в событие нажатия кнопки, чтобы показать текущее местоположение, а также предложить, если есть какие-либо изменения, чтобы передать текущие Lati и Longi в URL веб-службы после задания кодирования для события click.Заранее спасибо

Отредактировано: -

   - (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id   <MKAnnotation>) annotation
   {
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc]   initWithAnnotation:annotation reuseIdentifier:@""];
annView.pinColor = MKPinAnnotationColorGreen;
//annView.animatesDrop=TRUE;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
annView.enabled = YES;
annView.image = [UIImage imageNamed:@"flagg.png"];

UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self
                action:@selector(showDetails:)
      forControlEvents:UIControlEventTouchUpInside];
annView.rightCalloutAccessoryView = rightButton;    

NSLog(@"Created annotation at: %f %f",    ((CustomPlacemark*)annotation).coordinate.latitude, ((CustomPlacemark*)annotation).coordinate.longitude);

[annView addObserver:self
          forKeyPath:@"selected"
             options:NSKeyValueObservingOptionNew
             context:@"GMAP_ANNOTATION_SELECTED"];

[annView autorelease];

return annView;
  }

  //return nil;


    - (void)observeValueForKeyPath:(NSString *)keyPath
                  ofObject:(id)object
                    change:(NSDictionary *)change
                   context:(void *)context{

  NSString *action = (NSString*)context;

// We only want to zoom to location when the annotation is actaully selected. This   will trigger also for when it's deselected
if([[change valueForKey:@"new"] intValue] == 1 && [action   isEqualToString:@"GMAP_ANNOTATION_SELECTED"]) 
{
    if([((MKAnnotationView*) object).annotation isKindOfClass:[CustomPlacemark   class]])
    {
        CustomPlacemark *place = ((MKAnnotationView*) object).annotation;

        // Zoom into the location       
        [mapView setRegion:place.coordinateRegion animated:TRUE];
        NSLog(@"annotation selected: %f %f", ((MKAnnotationView*) object).annotation.coordinate.latitude, ((MKAnnotationView*) object).annotation.coordinate.longitude);
    }
    }
      }

Кнопка поиска (вызов веб-службы)

     CLLocationCoordinate2D location;
        //currentLocation = newLocation;

              float radius = [[arrayNo objectAtIndex:[pickerView   selectedRowInComponent:0]] floatValue];
    //NSURL *url = [[NSURL alloc] initWithString:@"http://www.hettich.com.au/hespdirectory/phpsqlsearch_genxml.php?lat=-33.853468&lng=150.94042160000004&radius=5"];

   NSString *url = [NSString   stringWithFormat:@"http://www.hettich.com.au/hespdirectory/phpsqlsearch_genxml.php?lat=%f&lng=%f&radius=%f",locationManager.location.coordinate.latitude,locationManager.location.coordinate.longitude,radius];
//NSLog(@"NSString *url");
NSLog(@"%@", url);
   NSURL *URL = [NSURL URLWithString:url];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:URL];
//Initialize the delegate.
XMLParser *parser = [[XMLParser alloc] initXMLParser];
//Set delegate
  [xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
if(success)

{       resultButton.userInteractionEnabled = YES;
          //    NSMutableArray* annotations = [[NSMutableArray alloc] init];

    for (int i = 0; i < [appDelegate.markers count]; i++)
{

    marker *aMarker = [appDelegate.markers objectAtIndex:i];
    location.latitude = [aMarker.lat floatValue];
    location.longitude =[aMarker.lng floatValue];
    AddressAnnotation *annob = [[AddressAnnotation alloc] initWithCoordinate:location];
    annob.title = aMarker.name;
    annob.subTitle = aMarker.address;
    [mapView addAnnotation:annob];
    [annob release];


    CLLocationCoordinate2D ausLoc = {location.latitude,location.longitude};         //for zoom in the showroom results region
    MKCoordinateSpan ausSpan = MKCoordinateSpanMake(0.108889, 0.169922);
    MKCoordinateRegion ausRegion = MKCoordinateRegionMake(ausLoc, ausSpan);
    NSLog(@"No Errors");
    mapView.region = ausRegion;



}


}

1 Ответ

0 голосов
/ 25 октября 2011

В вашем методе касания кнопки, вы должны сначала проверить, получил ли менеджер местоположения местоположение, а затем установить центр или регион карты на местоположение пользователя:

if (locationManager.location == nil)
{
    NSLog(@"user location not found yet or service disabled/denied");
}
else
{
    // Change map center (preserving current zoom level)...
    [mapView setCenterCoordinate:locationManager.location.coordinate animated:YES];

    // --OR--

    // Change map region using distance (meters)...
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance
                           (locationManager.location.coordinate, 1000, 1000);
    [mapView setRegion:region animated:YES];

    // --OR--

    // Change map region using span (degrees)...
    MKCoordinateSpan span = MKCoordinateSpanMake(0.001, 0.001);
    MKCoordinateRegion region = MKCoordinateRegionMake
                           (locationManager.location.coordinate, span);
    [mapView setRegion:region animated:YES];
}


В didUpdateToLocation метод, вы устанавливаете переменную currentLocation, но я не вижу в этом необходимости.У locationManager уже есть свойство location.

В любом случае неверно считать только абсолютные широты или долготы, превышающие 0,001, как «действительные», поскольку а) оно исключает местоположения вблизи экватора или основного меридиана (даже если вас интересует только Австралия, эта логика - неправильный путь), и б) лучше вместо этого проверить, является ли newLocation сам по себе nil.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...