2011-05-13 17 views
7

estoy teniendo una aplicación de mapa. Cuando una persona viaja desde su ubicación actual a una ubicación particular, quiero calcular la distancia cubierta por la persona, la velocidad actual de la persona, la velocidad promedio de la persona .puede ayudarme alguien a resolver este problema. Por favor, proporcione cualquier cantidad para resolver este problema. Graciascómo calcular la velocidad actual y la velocidad promedio del usuario que viaja desde la ubicación actual a una ubicación particular en el mapa en iphone

Respuesta

6

Mejore su tasa de aceptación. Use los siguientes métodos para obtener la distancia en millas o kilómetros. Tienes que declarar el temporizador en tu archivo de cabecera para sintetizarlo.

//SpeedViewController.h 
#import <UIKit/UIKit.h> 
#import <CoreLocation/CoreLocation.h> 
#import <MobileCoreServices/UTCoreTypes.h> 

@interface SpeedViewController : UIViewController <CLLocationManagerDelegate,UINavigationControllerDelegate> 
{ 
    CLLocationManager *locManager; 
    CLLocationSpeed speed; 
    NSTimer *timer; 

    CLLocationSpeed currentSpeed; 
    float fltDistanceTravelled; 
} 

@property (nonatomic,retain) NSTimer *timer; 

-(float)getDistanceInKm:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation; 
-(float)getDistanceInMiles:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation; 

@end 

//SpeedViewController.h 
#import "SpeedViewController.h" 
#define kRequiredAccuracy 500.0 //meters 
#define kMaxAge 10.0 //seconds 
#define M_PI 3.14159265358979323846264338327950288 /* pi */ 


@implementation SpeedViewController 

@synthesize timer; 
- (void)startReadingLocation { 
    [locManager startUpdatingLocation]; 
} 
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. 
- (void)viewDidLoad { 
    [super viewDidLoad]; 

    CLLocationManager *locationManager=[[CLLocationManager alloc] init]; 
    locationManager.delegate=self; 
    locationManager.desiredAccuracy=kCLLocationAccuracyBestForNavigation; 
    [locationManager startUpdatingLocation]; 
} 
- (void)didReceiveMemoryWarning { 
    // Releases the view if it doesn't have a superview. 
    [super didReceiveMemoryWarning]; 

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

- (void)viewDidUnload { 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 


- (void)dealloc { 
    [super dealloc]; 
} 

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    NSLog(@"new->%d old->%d",(newLocation==NULL),(oldLocation==NULL)); 

    if(newLocation && oldLocation) 
    { 
     fltDistanceTravelled +=[self getDistanceInKm:newLocation fromLocation:oldLocation]; 
    } 
} 

//this is a wrapper method to fit the required selector signature 
- (void)timeIntervalEnded:(NSTimer*)timer { 
    fltDistanceTravelled=0; 
    [self startReadingLocation]; 
} 


-(float)getDistanceInKm:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    float lat1,lon1,lat2,lon2; 

    lat1 = newLocation.coordinate.latitude * M_PI/180; 
    lon1 = newLocation.coordinate.longitude * M_PI/180; 

    lat2 = oldLocation.coordinate.latitude * M_PI/180; 
    lon2 = oldLocation.coordinate.longitude * M_PI/180; 

    float R = 6371; // km 
    float dLat = lat2-lat1; 
    float dLon = lon2-lon1; 

    float a = sin(dLat/2) * sin(dLat/2) + cos(lat1) * cos(lat2) * sin(dLon/2) * sin(dLon/2); 
    float c = 2 * atan2(sqrt(a), sqrt(1-a)); 
    float d = R * c; 

    NSLog(@"Kms-->%f",d); 

    return d; 
} 

-(float)getDistanceInMiles:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    float lat1,lon1,lat2,lon2; 

    lat1 = newLocation.coordinate.latitude * M_PI/180; 
    lon1 = newLocation.coordinate.longitude * M_PI/180; 

    lat2 = oldLocation.coordinate.latitude * M_PI/180; 
    lon2 = oldLocation.coordinate.longitude * M_PI/180; 

    float R = 3963; // km 
    float dLat = lat2-lat1; 
    float dLon = lon2-lon1; 

    float a = sin(dLat/2) * sin(dLat/2) + cos(lat1) * cos(lat2) * sin(dLon/2) * sin(dLon/2); 
    float c = 2 * atan2(sqrt(a), sqrt(1-a)); 
    float d = R * c; 

    NSLog(@"Miles-->%f",d); 

    return d; 
} 

@end 

Si usted tiene alguna otra consulta, por favor deje un comentario. No he probado esto en el dispositivo, pero lógicamente debería funcionar.

Espero que ayude.

+0

conozco el método startUpdatingLocation .is startReadingLocation y startUpdatingLocation mismo – Rani

+0

busqué el método startReadingLocation en la documentación del desarrollador pero contiene solamente stopupdatinglocation y startupdatinglocation. el método de ubicación de lectura es un método estándar o definido por el usuario – Rani

+0

@Rani Me disculpo, simplemente olvidé poner ese método en ese código. Actualizado el código –

2

el fin de determinar cualquier velocidad, usted querrá averiguar:

Distancia: Tome sus dos últimas lecturas de coordenadas geográficas (y el tiempo de cada uno fue grabado) para calcular la distancia entre ellos

Para hacer esto, puede leer sobre la teoría here, o puede verificar el código here.

Velocidad: Usando la distancia entre la última lectura de coordenadas GPS y la anterior, calcule la velocidad por la fórmula velocidad = distancia/duración. Entonces, la distancia que encontraste entre las dos coordenadas geográficas dividida por la duración en segundos o minutos o lo que sea. Entonces su respuesta será la velocidad es x millas o kilómetros por lo que sea.

Cuestiones relacionadas