准备两个CLLocation的对象,比如要计算某个位置与使用者当前位置的距离,
则其 中一个CLLocation是userLocation = [locationManager location],locationManager是CLLocationManager的实例,
并已执行[locationManager startUpdatingLocation];
然后计算这两个CLLocation的距离(已格式化成12.34 km
[NSString stringWithFormat:@"%0.2f km",[userLocation distanceFromLocation :location]/1000]

根据经纬度计算两点之间距离的Obcective-C代码

根据经纬度计算两点之间距离的Obcective-C代码,转自一位CocoaChina会员的博客(Link),其中其中er 就是地球椭球半径,对于google map使用 6378137 就可以了。 函数的调用非常简单, 几乎适用任何平台:)

#define PI 3.1415926double LantitudeLongitudeDist(double lon1,double lat1,         double lon2,double lat2){ double er = 6378137; // 6378700.0f; //ave. radius = 6371.315 (someone said more accurate is 6366.707) //equatorial radius = 6378.388 //nautical mile = 1.15078 double radlat1 = PI*lat1/180.0f; double radlat2 = PI*lat2/180.0f; //now long. double radlong1 = PI*lon1/180.0f; double radlong2 = PI*lon2/180.0f; if( radlat1 < 0 ) radlat1 = PI/2 + fabs(radlat1);// south if( radlat1 > 0 ) radlat1 = PI/2 - fabs(radlat1);// north if( radlong1 < 0 ) radlong1 = PI*2 - fabs(radlong1);//west if( radlat2 < 0 ) radlat2 = PI/2 + fabs(radlat2);// south if( radlat2 > 0 ) radlat2 = PI/2 - fabs(radlat2);// north if( radlong2 < 0 ) radlong2 = PI*2 - fabs(radlong2);// west //spherical coordinates x=r*cos(ag)sin(at), y=r*sin(ag)*sin(at), z=r*cos(at) //zero ag is up so reverse lat double x1 = er * cos(radlong1) * sin(radlat1); double y1 = er * sin(radlong1) * sin(radlat1); double z1 = er * cos(radlat1); double x2 = er * cos(radlong2) * sin(radlat2); double y2 = er * sin(radlong2) * sin(radlat2); double z2 = er * cos(radlat2); double d = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2)); //side, side, side, law of cosines and arccos double theta = acos((er*er+er*er-d*d)/(2*er*er)); double dist  = theta*er; return dist;}
1:获取当前手机经纬度@implementation CurrentLocation@synthesize locationManager;@synthesize target,callBack;

#pragma mark --#pragma mark Public

-(void) startUpdatingLocation{

    [[self locationManager] startUpdatingLocation];

}

#pragma mark --#pragma mark Memory management

-(void) dealloc{

    [super dealloc];

    [locationManager release];

}

#pragma mark --#pragma mark Location manager

/*

 Return a location manager -- create one if necessary.

*/

- (CLLocationManager *)locationManager {

if (locationManager != nil) {return locationManager;}

    locationManager = [[CLLocationManager alloc] init];

    [locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];

    [locationManager setDelegate:self];

return locationManager;

}

#pragma mark --#pragma mark CLLocationManagerDelegate methods

/*

 Conditionally enable the Add button:

 If the location manager is generating updates, then enable the button;

 If the location manager is failing, then disable the button.

*/

- (void)locationManager:(CLLocationManager *)manager

    didUpdateToLocation:(CLLocation *)newLocation

           fromLocation:(CLLocation *)oldLocation {

    NSLog(@"获取到经纬度!");

}

- (void)locationManager:(CLLocationManager *)manager

       didFailWithError:(NSError *)error {

        NSLog(@"获取失败!");

 }

@end

2:  获取当前手机经纬度的详细地址

@implementation AddressReverseGeoder

#pragma mark --#pragma mark Public
//根据经纬度开始获取详细地址信息- (void)startedReverseGeoderWithLatitude:(double)latitude longitude:(double)longitude{

    CLLocationCoordinate2D coordinate2D;

    coordinate2D.longitude = longitude;

    coordinate2D.latitude = latitude;

//

    MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:coordinate2D];

    geoCoder.delegate = self;

    [geoCoder start];

}

#pragma mark --#pragma mark MKReverseGeocoderDelegate methods

//获得地址信息

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {

    NSString *address = [NSString stringWithFormat:@"%@ %@ %@ %@ %@%@",

                                      placemark.country,

                                      placemark.administrativeArea,

                                      placemark.locality,

                                      placemark.subLocality,

                                      placemark.thoroughfare,

                                      placemark.subThoroughfare];

    NSLog(@"经纬度所对应的详细:%@", address);

    geocoder = nil;

}

//错误处理

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {

    NSLog(@"error %@" , error);

}

#pragma mark --#pragma mark Memory management

- (void)dealloc {

    [super dealloc];

}

@end


The distance is calculated between 2 CLLocations and not between to coordinates.

You need to use these coordinates to get the CLLocations for the respective coordinates using the following line of code

CLLocation*newLocation =[[CLLocation alloc] initWithCoordinate: newCoordinate altitude:1 horizontalAccuracy:1 verticalAccuracy:-1 timestamp:nil];

Similarly for the other coordinate and then you can calculate the distance between these two locations using the following line of code

CLLocationDistance kilometers =[newLocation distanceFromLocation:oldLocation]/1000;

In MkMapview calculate distance between two points

问:

Hi in iPhone App How to calculate distance between two points in MKMapView as shown in image

first point would be center point of visible map in mapview

2nd point would be any of corner of visible rect of mapview in mapview(here for example i have taken top left point)

答:

You can get lat/lon of the center with:

convertPoint:toCoordinateFromView:

loc1 and loc2 are both CLLocation objs.

CLLocationDistance dist =[loc1 distanceFromLocation:loc2];

So these two tips should help you. if you need some code, let me know :-)

答:

Here is how you can calculate the wanted distance :

// You first have to get the corner point and convert it to a coordinateMKMapRect mapRect = self.mapView.visibleMapRect;MKMapPoint cornerPointNW =MKMapPointMake(mapRect.origin.x, mapRect.origin.y);CLLocationCoordinate2D cornerCoordinate =MKCoordinateForMapPoint(cornerPointNW);

// Then get the center coordinate of the mapView (just a shortcut for convenience)CLLocationCoordinate2D centerCoordinate = self.mapView.centerCoordinate

// And then calculate the distanceCLLocationDistance distance =[cornerCoordinate distanceFromLocation:centerCoordinate];
计算走过的距离,并显示出来
问:

I trying to calculate the total distance travelled and output it to the View Controller, but the results are not as expected. Code is as follows:

MyCLController.m

-(void)locationManager:(CLLocationManager*)manager    didUpdateToLocation:(CLLocation*)newLocation           fromLocation:(CLLocation*)oldLocation{           validLocation = YES;

    if(!newLocation)     {        validLocation = NO;    }

    if(newLocation.horizontalAccuracy <0)    {        validLocation = NO;    }

    // Filter out points that are out of order    NSTimeInterval secondsSinceLastPoint =-[newLocation.timestamp timeIntervalSinceNow];    if(secondsSinceLastPoint <0)    {        validLocation = NO;    }

    if(validLocation == YES)    {        [self.delegate locationChange:newLocation :oldLocation];    }

NewWorkoutViewController.m

-(void)locationChange:(CLLocation*)newLocation:(CLLocation*)oldLocation{       

    CLLocationDistance meters =[newLocation distanceFromLocation:oldLocation];

    currentSpeed =([newLocation speed]*3600)/1000;    totalDistance =(totalDistance + meters)/1000;    totalDistanceMeters =  totalDistanceMeters + meters;    avgSpeed = totalDistance / counterInt;

    [speedLbl1 setText:[NSString stringWithFormat:@"%.3f", currentSpeed]];    [distanceLbl1 setText:[NSString stringWithFormat:@"%.3f", totalDistance]];

}

The problem is with my totalDistance, it doesn't appear to be adding to it each time, its as if its overwriting it, when I test in the car I can see values of 10 / 20 meters between coordinates, so this indicates that distanceFromLocation appears to be working.

Anyone any thoughts ?

答:

Try this :

totalDistance = totalDistance +(meters /1000);

instead of this

totalDistance =(totalDistance + meters)/1000;

The way you had it, totalDistance was being divided by 1000 each time i.e. if you're travelling 10m each time :

totalDistance =(0+10)/1000=0.01;totalDistance =(0.01+10)/1000=0.01001//!< You expected this to be 0.02!totalDistance =(0.01001+10)/1000=0.01001001//!< You expected this to be 0.03!

CLLocation的distanceFromLocation方法计算地图上距离 (汇总)相关推荐

  1. php 地图两点距离计算,计算地图上两点间的距离PHP类

    计算地图上两点间的距离,使用的是谷歌地图 class GeoHelper { /** * @param int $lat1 * @param int $lon1 * @param int $lat2 ...

  2. 计算器计算经纬距离_经纬度距离角度计算器计算地图点距离角度教程

    经纬度距离角度计算器是一款好用的地图距离计算器.使用本软件可以轻松根据地图上的两个点的经纬度数据来计算地图中两个点之间的距离: 进入下载经纬度距离角度计算器 2.0 免费版 大小:12.73 MB 日 ...

  3. java 点与线的距离_计算地图上点与线段距离

    将地球看做一个标准球体,计算点到线段的距离. 计算两点间的球面距离 /** * * a点经度,a点纬度,b点经度,b点纬度 * */ public static double calcP2P(doub ...

  4. 计算地图两个点的距离 经纬度距离计算

    一.java public class DistanceUtil {/*** 转化为弧度(rad)*/private static double rad(double d) {return d * M ...

  5. 地图上点到范围的最短距离算法

    今天是七夕,应该留点什么才对.恰好遇到地图上点与多边形的距离计算问题,如果是Oracle Spatial控件函数计算的话,有如下几个缺点:耗时久.计算范围有局限.所以我想要在前端地图上计算该点到范围的 ...

  6. 依据地图上的经纬度坐标计算某个点到多边形各边的距离

    http://www.th2w.com/article/85 依据地图上的经纬度坐标计算某个点到多边形各边的距离 最近公司有一个需求:依据地图上的经纬度坐标计算某个点到多边形各边的距离. 主要原理: ...

  7. 最新版人脸识别小程序 图片识别 生成二维码签到 地图上选点进行位置签到 计算签到距离 课程会议活动打卡日常考勤 上课签到打卡考勤口令签到

    技术选型 1,前端 小程序原生MINA框架 css JavaScript Wxml 2,管理后台 云开发Cms内容管理系统 web网页 3,数据后台 小程序云开发 云函数 云开发数据库(基于Mongo ...

  8. php地图距离计算,php百度地图计算两地现实距离

    请自行到百度地图官网申请您的ak <!--前端获取手机经纬度的代码--> <!--<!DOCTYPE html>--> <!--<html lang=& ...

  9. 【游戏设计图形学】在地图上生成蜿蜒河流的两种方法

    引言 在开发游戏时,我们经常需要用到随机生成的地形,而河流是其中不可或缺的一部分.本文章将探讨如何在地图上生成河流. 河流生成的自然原因 高山积雪,地下水,雨水是河流发源的主要原因,而由于雨水形成的小 ...

最新文章

  1. 漫画 | 产品经理的八大罪状
  2. Nginx源码分析:3张图看懂启动及进程工作原理
  3. 分页控件-ASP.NET(AspNetPager)
  4. 虚函数、纯虚函数、虚函数与析构函数
  5. Counting Bits(Difficulty: Medium)
  6. micropython中文社区-micropython支持中文啦!
  7. 万能电商Banner素材模板,一切产品为王
  8. java 过滤js事件_java中的过滤器与监听器
  9. Pandas——处理丢失的数据(含NaN的数据)
  10. 用python做时间序列预测一:初识概念
  11. Contki 相关链接备忘
  12. 【JAVA】数字相加
  13. Mysql深入浅出学习
  14. 什么是 Hook 技术
  15. iOS | Swift图片剪切圆角
  16. CES Asia:MR混合现实引发行业热议
  17. 执行方案--交付型项目如何过渡实现项目顺利重装
  18. 一整套的软件测试学习视频、包括web自动化、APP自动化、接口自动化,以及python语言,基础知识讲解和项目实践,学习后可收获python、web/APP/接口自动化测试。
  19. 推荐系统 --- 推荐算法 --- 基于用户行为的推荐算法 - 协同过滤算法
  20. 时序图和流程图的区别

热门文章

  1. 基于ArduinoLeonardo板子的BadUSB攻击实战
  2. 【编程练习】C语言debug合集
  3. 不懂技术系列--如何快速调试html5页面/手机页面
  4. android keytool 不是内部命令或外部命令在 (win7下不能用的解决方法)
  5. 使用tortoise git管理gitolite版本库
  6. Android -- 消息处理机制源码分析(Looper,Handler,Message)
  7. Jake Coco - Under The Covers, Vol. 2 {2011}
  8. ElasticSearch之集群原理
  9. 支付宝对接3(收费问题)
  10. Application Architecture Guide 2.0 - CH 19 - Mobile Applications(5)