ios開發之計算地圖上兩地距離

CLLocation *lastLocation = [[CLLocation alloc] initWithLatitude:coords.latitude longitude:coords.longitude];
  CLLocation *nowLocation = [[CLLocation alloc] initWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
 
    int distanceMeters = [lastLocation distanceFromLocation:nowLocation];
             
                if(appDelegate.isKMOrMILE == 0)
                {
                    [cardistanceLabel setText:[NSString stringWithFormat:@"%d KM",distanceMeters/1000]];//公里
                }
                else if(appDelegate.isKMOrMILE == 1)
                {
                    int data = (distanceMeters/1000)/1.6093;
                    [cardistanceLabel setText:[NSString stringWithFormat:@"%d MILE",data]];//英里
                }


已知兩地經緯度 計算兩地之間的距離:
//    地圖顯示當前位置:
    mapView.showsUserLocation=YES;
    CLLocationManager *locationManager = [[CLLocationManager alloc] init];//創建位置管理器
    locationManager.delegate=self;//設置代理
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;//指定需要的精度級別爲最佳精度
    locationManager.distanceFilter=1000.0f;//設置距離篩選器爲任何移動都要發送更新
    [locationManager startUpdatingLocation];//啓動位置管理器
    MKCoordinateSpan theSpan;
    //地圖的範圍 越小越精確
    theSpan.latitudeDelta=0.05;
    theSpan.longitudeDelta=0.05;
    MKCoordinateRegion theRegion;
    theRegion.center=[[locationManager location] coordinate];
    theRegion.span=theSpan;
    [mapView setRegion:theRegion];
    [locationManager release];
    
    MKUserLocation *usrLoc=mapView.userLocation;
    CLLocationCoordinate2D usrCoordinate=usrLoc.location.coordinate;
    NSLog(@"la==%f lo==%f",usrCoordinate.latitude,usrCoordinate.longitude);
    
//   已知兩點的經緯度,計算出兩地距離:
    CLLocation *location1 = [[[CLLocation alloc] initWithLatitude:usrCoordinate.latitude longitude:usrCoordinate.longitude] autorelease];
    CLLocation *location2 = [[[CLLocation alloc] initWithLatitude:36.676445 longitude:117.106793] autorelease];
    NSLog(@"JULI====%.0f km", [location1 distanceFromLocation:location2]);//4502


取小數點後兩位(四捨五入),輸出:
NSLog(@"%.02f km",4478.442312);




軟件開發程序員博客文章收藏網

http://www.programgo.com/tag/ios/950044682/4/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章