Подтвердить что ты не робот

Получить местоположение пользователя из MKMapView

Можно ли использовать собственный менеджер местоположений MKMapView, чтобы вернуть текущее местоположение пользователей в веб-сервис?

У меня есть mapView.showsUserLocation=YES;, и это возвращает истинную синюю точку в моем местоположении, но в симуляторе его Купертино - это прекрасно, но когда я смотрю

mapView.userLocation.coordinate.latitude, его значение равно 180, тогда как CLLocationManager возвращает правильный, 37.3317.

Я хочу, чтобы у меня не было нескольких менеджеров местоположений для моих трех вкладок, поэтому полезно было бы использовать mapViews own.

Спасибо.

4b9b3361

Ответ 1

Вы можете получить местоположение пользователя из MKMapView. У вас просто отсутствует свойство при его изъятии. Это должно быть:

mapView.userLocation.location.coordinate.latitude;

userLocation сохраняет только атрибут местоположения CLLocation и атрибут обновления BOOL. Чтобы получить координаты, вы должны перейти к атрибуту location.

-Drew

РЕДАКТИРОВАТЬ: Местоположение пользователя MKMapView не обновляется, пока карта не закончит загрузку, а проверка слишком рано вернет нули. Чтобы этого избежать, я предлагаю использовать метод MKMapViewDelegate -(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation.

Ответ 2

Итак, чтобы использовать уникальный CLLocateManager, вы можете создать класс для делегата для всех ваших карт. Поэтому вместо выполнения:

self.locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;

Сделайте что-то вроде:

self.locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = mySharedDelegate;

Где mySharedDelegate - ваш класс со всеми методами делегирования CLLocationManager.

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

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

Когда этот метод вызывается, это связано с тем, что GPS нашел новое местоположение, и поэтому синяя точка будет перемещена туда, а у пользователяLocation будет новая координата.

Используйте следующий метод для вашего делегата CLLocationManager для регистрации текущего местоположения при его обнаружении:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"---------- locationManager didUpdateToLocation");
    location=newLocation.coordinate;

    NSLog(@"Location after calibration, user location (%f, %f)", _mapView.userLocation.coordinate.latitude, _mapView.userLocation.coordinate.longitude);
}

У вас есть идея?

Приветствия,
VFN

Ответ 3

    - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
    {
        NSLog(@"welcome into the map view annotation");

        // if it the user location, just return nil.
        if ([annotation isKindOfClass:[MyMapannotation class]])
        {
            MyMapannotation *annotation12=(MyMapannotation *)annotation;
            // try to dequeue an existing pin view first
            static NSString* AnnotationIdentifier = @"AnnotationIdentifier";
            MKPinAnnotationView* pinView = [[MKPinAnnotationView alloc]
                                            initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] ;
            pinView.animatesDrop=YES;
            pinView.canShowCallout=YES;
            pinView.pinColor=MKPinAnnotationColorPurple;
            pinView.tag=annotation12.tag;

            UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
            [rightButton setTitle:annotation.title forState:UIControlStateNormal];
            rightButton.tag=annotation12.tag;
            [rightButton addTarget:self
                            action:@selector(showDetails:)
                  forControlEvents:UIControlEventTouchUpInside];
            pinView.rightCalloutAccessoryView = rightButton;
            UIImageView *profileIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"artpin"]];
            pinView.image = profileIconView.image;
            return pinView;
        }
        else
            return nil;
     }

    -(IBAction)showDetails:(id)sender
    {
        UIButton *btn=(UIButton *)sender;

    }


    -(void)Load_mapview
    {


        for (int i=0; i<[arr_nearby count]; i++)
        {
            NSNumber *latitude = [[[[arr_nearby objectAtIndex:i] valueForKey:@"geometry"] valueForKey:@"location"] valueForKey:@"lat"];

            NSNumber *longitude = [[[[arr_nearby objectAtIndex:i] valueForKey:@"geometry"] valueForKey:@"location"] valueForKey:@"lng"];

            NSString *title = [[arr_nearby objectAtIndex:i] valueForKey:@"name"];

            //Create coordinates from the latitude and longitude values

            CLLocationCoordinate2D coord;

            coord.latitude = latitude.doubleValue;

            coord.longitude = longitude.doubleValue;

            MyMapannotation *annotation = [[MyMapannotation alloc] initWithTitle:title AndCoordinate:coord andtag:i];
            [_map_nearby addAnnotation:annotation];


          //  [annotations addObject:annotation];

        }

        [self zoomToLocation];


    }
    -(void)zoomToLocation

    {

        CLLocationCoordinate2D zoomLocation;

        zoomLocation.latitude = [[[[[arr_nearby objectAtIndex:0] valueForKey:@"geometry"] valueForKey:@"location"] valueForKey:@"lat"] floatValue];

        zoomLocation.longitude= [[[[[arr_nearby objectAtIndex:0] valueForKey:@"geometry"] valueForKey:@"location"] valueForKey:@"lng"] floatValue];

        MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 7.5*5,7.5*5);

        [_map_nearby setRegion:viewRegion animated:YES];

        [_map_nearby regionThatFits:viewRegion];

    }

//
//  MyMapannotation.h
//  IOS_Googgle
//
//  Created by Vivek Chauhan on 27/06/16.
//  Copyright (c) 2016 anand. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>


@interface MyMapannotation : NSObject <MKAnnotation>

@property (nonatomic,copy) NSString *title;
@property (nonatomic,assign) int tag;


@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;

-(id) initWithTitle:(NSString *) title AndCoordinate:(CLLocationCoordinate2D)coordinate andtag:(int)tagofbutton;


@end


//
//  MyMapannotation.m
//  IOS_Googgle
//
//  Created by Vivek Chauhan on 27/06/16.
//  Copyright (c) 2016 anand. All rights reserved.
//

#import "MyMapannotation.h"

@implementation MyMapannotation

@synthesize coordinate=_coordinate;

@synthesize title=_title;
@synthesize tag=_tag;


-(id) initWithTitle:(NSString *) title AndCoordinate:(CLLocationCoordinate2D)coordinate andtag:(int)tagofbutton

{

    self = [super init];

    _title = title;

    _coordinate = coordinate;
    _tag=tagofbutton;

    return self;

}
@end