Поиск местоположения с помощью iPhone в городских условиях - PullRequest
2 голосов
/ 28 марта 2011

Мы разрабатываем приложение для iPhone, и нам нужно знать приблизительное местоположение пользователя. Мы используем CoreLocation. Мы можем делать это хорошо в пригородных условиях, но в Нью-Йорке - мы не можем получить информацию о долготе / широте.

Мы подозреваем, что это связано с тем, что сигналы GPS слабые среди высотных зданий ... Но разве мы не можем получить некоторую приблизительную информацию о местоположении?

Есть идеи, что может вызвать / исправить это? Спасибо.

#import "RootViewController.h"
#import "SlickEatsAppDelegate.h"
#import "SlickEatsWelcomePage.h"
#import "XMLParserShowTodaysOffer.h"
#import "SlickEatsSplashScreen.h"

@implementation RootViewController
@synthesize locationManager,currentLocation,appDelegate;
@synthesize getStartedButton,splashLogoImageView,howItWorkImageView,workButton,infoView;
@synthesize xmlParserShowTodaysOffer;//activityIndicator
#pragma mark -
#pragma mark View lifecycle



- (void)viewDidLoad {
    [super viewDidLoad];

    [self connectedToNetwork];

    self.navigationController.navigationBar.hidden = TRUE;
    if(locationManager == nil)
    {
        [[self locationManager] startUpdatingLocation];
    }

    //[self.view addSubview:SlickEatsView];
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}



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

/*-(IBAction)getStartedButton_Clicked:(id)sender
{
    activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.activityIndicator.frame = CGRectMake(135, 150, 40, 40);

    [self.view addSubview:activityIndicator];
    if (self.activityIndicator.isAnimating == NO)
    {
        [self.activityIndicator startAnimating];
    }
    /*if(locationManager == nil)
    {
        [[self locationManager] startUpdatingLocation];
    }*/
    /*SlickEatsWelcomePage *welcomePage = [[SlickEatsWelcomePage alloc]initWithNibName:@"SlickEatsWelcomePage" bundle:nil];
    appDelegate = (SlickEatsAppDelegate *)[[UIApplication sharedApplication]delegate];

    xmlParserShowTodaysOffer = [XMLParserShowTodaysOffer alloc];
    xmlParserShowTodaysOffer.currentCity = appDelegate.myCurrentCity;
    xmlParserShowTodaysOffer.currentLatitude = appDelegate.myCurrentLatitude;
    xmlParserShowTodaysOffer.currentLongitude = appDelegate.myCurrentLongitude;
    [xmlParserShowTodaysOffer initXMLParser];
    [xmlParserShowTodaysOffer release];

    [self.navigationController pushViewController:welcomePage animated:YES];
    [welcomePage release];
    [activityIndicator removeFromSuperview];
    //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"9763912503"]];
}*/
- (CLLocationManager *)locationManager {


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


}

#pragma mark -
#pragma mark CLLocationManagerDelegate Methods

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
    appDelegate = (SlickEatsAppDelegate *)[[UIApplication sharedApplication]delegate];
    int degrees = newLocation.coordinate.latitude;
    double decimal = fabs(newLocation.coordinate.latitude - degrees);
    int minutes = decimal * 60;
    double seconds = decimal * 3600 - minutes * 60;
    NSString *lat = [NSString stringWithFormat:@"%d° %d' %1.4f\"", 
                     degrees, minutes, seconds];

    //latLabel.text = lat;
    NSLog(@"Current..Latitude::%@",lat);
    NSString *CurrentLatitude = [NSString stringWithFormat:@"%lf",newLocation.coordinate.latitude]; 
    NSLog(@"Current..Latitude::%@",CurrentLatitude);
    //self.myCurrentLatitude=lat;

    degrees = newLocation.coordinate.longitude;
    decimal = fabs(newLocation.coordinate.longitude - degrees);
    minutes = decimal * 60;
    seconds = decimal * 3600 - minutes * 60;
    NSString *longt = [NSString stringWithFormat:@"%d° %d' %1.4f\"", degrees, minutes, seconds];
    //longLabel.text = longt;
    NSLog(@"Current..Longitude::%@",longt);

    NSString *CurrentLongitude = [NSString stringWithFormat:@"%lf",newLocation.coordinate.longitude];
    NSLog(@"Current..Longitude::%@",CurrentLongitude);

    appDelegate.myCurrentLatitude = CurrentLatitude;
    appDelegate.myCurrentLongitude = CurrentLongitude;


    MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
    geoCoder.delegate = self;
    [geoCoder start];

}

// this delegate is called when the reverseGeocoder finds a placemark
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
    MKPlacemark * myPlacemark = placemark;
    // with the placemark you can now retrieve the city name
    NSString *city =[ myPlacemark.addressDictionary objectForKey:(NSString*) kABPersonAddressCityKey];
    // NSString *city = (NSString *)[myPlacemark.locality length];
    NSLog(@"Current Add::%@",city);
    appDelegate.myCurrentCity = city;

    //[self sendLocation];
}

// this delegate is called when the reversegeocoder fails to find a placemark
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
    NSLog(@"reverseGeocoder:%@ didFailWithError:%@", geocoder, error);
}



- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"error%@",error);
    switch([error code])
    {
        case kCLErrorNetwork: // general, network-related error
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"please check your network connection or that you are not in airplane mode" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
        }
            break;
        case kCLErrorDenied:{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"user has denied to use current Location " delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
        }
            break;
        default:
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"unknown network error" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
        }
            break;
    }
}


-(void)sendLocation
{

    NSLog(@"in Send Location..");

    SlickEatsWelcomePage *welcomePage = [[SlickEatsWelcomePage alloc]initWithNibName:@"SlickEatsWelcomePage" bundle:nil];
    appDelegate = (SlickEatsAppDelegate *)[[UIApplication sharedApplication]delegate];

    xmlParserShowTodaysOffer = [XMLParserShowTodaysOffer alloc];
    xmlParserShowTodaysOffer.currentCity = appDelegate.myCurrentCity;
    xmlParserShowTodaysOffer.currentLatitude = appDelegate.myCurrentLatitude;
    xmlParserShowTodaysOffer.currentLongitude = appDelegate.myCurrentLongitude;
    [xmlParserShowTodaysOffer initXMLParser];
    [xmlParserShowTodaysOffer release];

    [self.navigationController pushViewController:welcomePage animated:YES];
    [welcomePage release];
    //[locationManager release];
}

-(IBAction)workButton_clicked:(id)sender
{
    /*activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.activityIndicator.frame = CGRectMake(135, 150, 40, 40);

    [self.splashLogoImageView addSubview:activityIndicator];
    if (self.activityIndicator.isAnimating == NO)
    {
        [self.activityIndicator startAnimating];
    }*/
    SlickEatsSplashScreen *intro = [[SlickEatsSplashScreen alloc]initWithNibName:@"SlickEatsSplashScreen" bundle:nil];
    [self.navigationController pushViewController:intro animated:YES];
    [intro release];
    //[activityIndicator removeFromSuperview];
}

- (void)connectedToNetwork {

    BOOL aflag= ([NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.co.in/"]]!=NULL)?YES:NO;



    if (!aflag) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Sorry!....You are not connected to network " 
                              delegate:self cancelButtonTitle:@"Exit" otherButtonTitles:nil];
        [alert show];
        [alert release];

    }
}


/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/

/*
 // Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
 */




/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/




#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
    [workButton release];
    [howItWorkImageView release];
    [splashLogoImageView release];
    [getStartedButton release];
    [locationManager release];
}


@end

Ответы [ 2 ]

0 голосов
/ 28 марта 2011

Я подозреваю, что вы запрашиваете точность, подобную GPS, когда чип GPS не получает никаких сигналов из-за высотных зданий:

locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters; // 100 m

Попробуйте закомментировать вышеприведенное утверждение и проверить его в поле - посмотрите, насколько точны получаемые вами координаты.

0 голосов
/ 28 марта 2011

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

...