IOS, передавая var с широтой и долготой с приведением типа к CLLocationCoordinate2D, показывает разные местоположения на картах

У меня возникает эта странная проблема при передаче значений в CLLocationCoordinate2D из переменной. Но если я использую те же значения, жестко запрограммированные. Тогда он работает идеально.

Я получаю значения с этой страницы. http://localsearch.azurewebsites.net/api/Locations

сохраните его в массиве NSMutable как Dicts. Все значения сохраняются и извлекаются без проблем. Я извлекаю все в виде строк, а затем печатаю их на все, что необходимо. что в этом случае было бы lat и long для удвоения или поплавка (я пробовал оба результата в одном и том же результате).

Я печатаю значения до того, как они попадут в CL CLLocationCoordinate2D. и они в порядке. Те же значения, что и в жестко заданных. Я сделал несколько скриншотов и надеюсь, что кто-то сталкивался с этой проблемой.

На этом снимке экрана показано значение, которое моя координатная переменная получает из жестко заданных выше значений. Это тот, который показывает жестко заданные значения

Теперь на этом снимке экрана показано значение, которое моя переменная coord2 получает из переменных, которые хранят те же значения, которые ранее передавались жестко запрограммированными. Внизу вы можете видеть, что NSLog печатает те же значения. Но по какой-то причине они получают разные значения.

Это то, что показано с переданными значениями.

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

Спасибо за помощь. PS: дайте мне знать, если вам, ребята, нужно, чтобы я добавил фрагменты кода того, что я сделал. Не уверен, что это необходимо, поскольку это конкретное место, где значения просто не совпадают.

это мой код таблицы

-(void)viewWillAppear:(BOOL)animated{
    //Fetching data from API URL
    NSURL *locationURL = [NSURL URLWithString:JSON_URL];
    NSData *jsonData = [NSData dataWithContentsOfURL:locationURL];
    NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
    for (NSDictionary *locationsDictionary in dataDictionary){
        LocationObjects *currentLocation = [[LocationObjects alloc] initWithId:[locationsDictionary objectForKey:@"ID"]
                                                                          Name:[locationsDictionary objectForKey:@"Name"]
                                                                      Latitude:[locationsDictionary objectForKey:@"Latitude"]
                                                                     Longitude:[locationsDictionary objectForKey:@"Longitude"]
                                                                       Address:[locationsDictionary objectForKey:@"Address"]
                                                                   ArrivalTime:[locationsDictionary objectForKey:@"ArrivalTime"]];

        [self.objectHolderArray addObject:currentLocation];
    }
    //[objectHolderSortedArray arrayByAddingObjectsFromArray:[self sortArray]];
}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.contentInset = UIEdgeInsetsMake(20.0f, 0.0f, 0.0f, 0.0f);
    UIBarButtonItem *btn=[[UIBarButtonItem alloc] initWithTitle:@"Back"
                                                          style:UIBarButtonItemStylePlain
                                                         target:self
                                                         action:@selector(dismissView)];
    self.navigationItem.leftBarButtonItem=btn;


}
-(NSMutableArray *)objectHolderArray{
    if(!objectHolderArray) objectHolderArray = [[NSMutableArray alloc]init];
    return objectHolderArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //NSLog(@"returns the count in the array: %lu", (unsigned long)[self.objectHolderArray count]);
    return [self.objectHolderArray count];
}
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        static NSString *CellIdentifier = @"Cell";
        LocationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[LocationTableViewCell alloc] initWithFrame:CGRectZero];
        }


        LocationObjects *currentLocation = [self.objectHolderArray objectAtIndex:indexPath.row];

        cell.lblId.text = [NSString stringWithFormat:@"ID: %@",currentLocation.Id];
        cell.lblcurrentName.text = [NSString stringWithFormat:@"Name: %@",currentLocation.Name];
        cell.lblgivenAddress.text = [NSString stringWithFormat:@"Address: %@",currentLocation.Address];


        return cell;
    }

    #pragma mark - Table View Delegate
    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

        [tableView deselectRowAtIndexPath:indexPath animated:YES];

        LocationObjects *currentLocation = [self.objectHolderArray objectAtIndex:indexPath.row];
        //NSLog(@"indexPath.row: %lu", indexPath.row);
        if(!LocationMapVC) LocationMapVC = [[LocationMapViewController alloc] init];
        LocationMapVC.name = [NSString stringWithFormat:@"Name: %@",currentLocation.Name];
        //NSLog(@"Name: %@", [NSString stringWithFormat:@"Name: %@",currentLocation.Name]);
        LocationMapVC.address = [NSString stringWithFormat:@"Address: %@",currentLocation.Address];



        LocationMapVC.latitude = [NSString stringWithFormat:@"Latitude: %@",currentLocation.Latitude];
        NSLog(@"Latitude: %@", [NSString stringWithFormat:@"Latitude: %@",currentLocation.Latitude]);

        LocationMapVC.longitude = [NSString stringWithFormat:@"Longitude: %@",currentLocation.Longitude];
        NSLog(@"Longitude: %@", [NSString stringWithFormat:@"Longitude: %@",currentLocation.Longitude]);

        //http://stackoverflow.com/questions/33758859/present-view-controller-not-working-with-ios-9
        [self presentViewController:LocationMapVC animated:YES completion:nil];
        LocationMapVC = nil;
    }

и это мой код просмотра карты.

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    //late instantiation
    if (!mapView) {
        mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
    }

    //dismiss modal button
    UIButton *done = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [done addTarget:self action:@selector(dismissView) forControlEvents:UIControlEventTouchDown];
    [done setTitle:@"Done" forState:UIControlStateNormal];
    done.frame = CGRectMake(((self.view.frame.size.width)/2)+10, (self.view.frame.size.height)-60, 160, 40);
    done.backgroundColor = [UIColor blackColor];

    //direction modal button
    UIButton *directions = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [directions addTarget:self action:@selector(showRouteVC) forControlEvents:UIControlEventTouchDown];
    [directions setTitle:@"Route" forState:UIControlStateNormal];
    directions.frame = CGRectMake(((self.view.frame.size.width)/2)-170, (self.view.frame.size.height)-60, 160, 40);
    directions.backgroundColor = [UIColor blackColor];

    //Location Manager
    locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [locationManager requestWhenInUseAuthorization];
    }
    //[locationManager requestLocation];
    //[locationManager startUpdatingLocation];
    self.mapView.delegate = self;
    mapView.mapType = MKMapTypeStandard;
    //mapView.showsUserLocation = YES;
    self.mapView.zoomEnabled = YES;

    //MAPING VALUES
    CLLocationCoordinate2D coord = {.latitude =  41.883976, .longitude =  -87.639346};
    NSLog(@"In location map the Latitude: %@ and Longitutude: %@", latitude, longitude);
    CLLocationCoordinate2D coord2 = {.latitude = [latitude doubleValue],.longitude = [longitude doubleValue]};

    MKCoordinateSpan span = {.latitudeDelta =  0.03, .longitudeDelta =  0.03};

    MKCoordinateRegion region = {coord, span};


    //implementing annotations base of the info passed.
    annotation = [[Annotation alloc] initWithAnnotation:coord title:name subtitle:address];


    [self.mapView addAnnotation:annotation];
    [self.mapView setRegion:region animated:YES];

    //adding subviews.
    [mapView setRegion:region];
    [self.view addSubview:mapView];
    [self.view addSubview:done];
    [self.view addSubview:directions];
}

person Jiraheta    schedule 07.03.2016    source источник
comment
Все в исходном вопросе. У меня есть эта странная проблема при передаче значений в CLLocationCoordinate2D из переменной. Но если я использую те же значения, жестко запрограммированные. Тогда он работает идеально. Я получаю значения с этой страницы. localsearch.azurewebsites.net/api/Locations сохраняет значения в массиве NSMutable как словари. Все значения сохраняются и извлекаются без проблем. Согласно тому, что я читал и проводил исследования, вы должны передать двойное значение в CLLocationCoordinate2D, поэтому я привожу тип к двойному.   -  person Jiraheta    schedule 08.03.2016
comment
извлечение данных и их сохранение в виде словаря в массиве NSMutable. Я вспоминаю данные, основанные на клике на IndexPath.row. Передайте значение в VC карты, а затем приведите его к типу double. Если я жестко закодирую значения. Я получаю местоположение. Если я передам переменные, то окажусь где-то в океане.   -  person Jiraheta    schedule 08.03.2016
comment
Смотреть. Есть только одна интересная строка, вот эта: CLLocationCoordinate2D coord2 = {.latitude = [latitude doubleValue],.longitude = [longitude doubleValue]}; Это значение выходит, как мы теперь знаем, как {0,0}. Итак, теперь нам нужно знать: что такое latitude, например, что [latitude doubleValue] есть 0? И ответ таков: все, что не может быть легко преобразовано в двойника. Поэтому вам нужно точно определить, что такое latitude есть. И когда вы узнаете, вы поймете, почему это происходит. Ты видишь?   -  person matt    schedule 08.03.2016


Ответы (1)


В конце концов, я смог разобраться благодаря Мэтту и некоторым другим помощникам.

ошибка, которую я совершал, здесь.

    LocationMapVC.latitude = [NSString stringWithFormat:@"Latitude: %@",currentLocation.Latitude];
    LocationMapVC.longitude = [NSString stringWithFormat:@"Longitude: %@",currentLocation.Longitude];

Я передавал stringWithFormat и добавлял к строкам «Широту:» и «Долготу:». Очевидно, что на другом конце это нельзя превратить в двойное значение, возвращающее 0,0. Так что исправить. Все, что нужно было сделать, это передать значение без stringWithFormat. Это выглядит так.

    LocationMapVC.latitude = currentLocation.Latitude;
    LocationMapVC.longitude = currentLocation.Longitude;

и это был конец этого. Спасибо, Мэтт, за подсказку, где искать, чтобы решить эту проблему. Надеюсь, это поможет кому-то в будущем.

person Jiraheta    schedule 08.04.2016