У меня возникает эта странная проблема при передаче значений в 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];
}
CLLocationCoordinate2D coord2 = {.latitude = [latitude doubleValue],.longitude = [longitude doubleValue]};
Это значение выходит, как мы теперь знаем, как{0,0}
. Итак, теперь нам нужно знать: что такоеlatitude
, например, что[latitude doubleValue]
есть0
? И ответ таков: все, что не может быть легко преобразовано в двойника. Поэтому вам нужно точно определить, что такоеlatitude
есть. И когда вы узнаете, вы поймете, почему это происходит. Ты видишь? - person matt   schedule 08.03.2016