随记(九)--确定两个地点的经纬度,自制驾车路线并计算其距离

使用地图,使用最多的也是百度地图API,以前使用百度地图只是表面地引用一下方法,很少点进方法或者对应属性的文件中,去查看其对应的说明与含义。

1.百度地图两点之间的距离

 1 /**
 2
 3  *计算指定两点之间的距离
 4
 5  *@param a 第一个坐标点
 6
 7  *@param b 第二个坐标点
 8
 9  *@return 两点之间的距离,单位:米
10
11  */
12
13 UIKIT_EXTERN CLLocationDistance BMKMetersBetweenMapPoints(BMKMapPoint a, BMKMapPoint b);

BMKMetersBetweenMapPoints方法只是两个经纬度之间的直线距离

2.路线实际距离

 1 ///此类表示一条驾车路线
 2 @interface BMKDrivingRouteLine : BMKRouteLine{
 3     bool                 _isSupportTraffic;//从2.7.0开始,废弃
 4     NSArray*             _wayPoints;
 5 }
 6 ///该路线所在区域是否含有交通流量信息,从2.7.0开始,废弃
 7 @property (nonatomic) bool isSupportTraffic;
 8 ///路线途经点列表,成员类型为BMKPlanNode
 9 @property (nonatomic, strong) NSArray* wayPoints;
10 @end
 1 ///此类表示路线数据结构的基类,表示一条路线,路线可能包括:路线规划中的换乘/驾车/步行路线
 2 ///此类为路线数据结构的基类,一般关注其子类对象即可,无需直接生成该类对象
 3 @interface BMKRouteLine : NSObject{
 4     int                  _distance;
 5     BMKTime*             _duration;
 6     BMKRouteNode*        _starting;
 7     BMKRouteNode*        _terminal;
 8     NSString*            _title;
 9     NSArray*             _steps;
10 }
11 ///路线长度 单位: 米
12 @property (nonatomic) int distance;
13 ///路线耗时 单位: 秒
14 @property (nonatomic, strong) BMKTime* duration;
15 ///路线起点信息
16 @property (nonatomic, strong) BMKRouteNode* starting;
17 ///路线终点信息
18 @property (nonatomic, strong) BMKRouteNode* terminal;
19 ///路线名称(预留字段,现为空)
20 @property (nonatomic, strong) NSString* title;
21 ///路线中的所有路段,成员类型为BMKWalkingStep,BMKDrivingStep,BMKTransitStep
22 @property (nonatomic, strong) NSArray* steps;
23 @end

将MBKDrivingRouteLine实例化,通过distance属性获取实际驾车路线距离

长话段说,直接贴上我的代码

在XXX.h文件中

 1 #import <UIKit/UIKit.h>
 2 #import "BMapKit.h"
 3
 4 @interface XXXViewController : UIViewController
 5
 6 //@property (weak, nonatomic) IBOutlet BMKMapView *mapView;
 7
 8
 9 @property (nonatomic, assign) CLLocationCoordinate2D startCoor;
10 @property (nonatomic, assign) CLLocationCoordinate2D endCoor;
11 @property (nonatomic, copy) NSString *addrName;
12
13 @end

在XXX.m文件中

  1 #import "XXX.h"
  2 #import "UIImage+Rotate.h"
  3
  4 #import <MapKit/MapKit.h>
  5
  6 #define MYBUNDLE_NAME @ "mapapi.bundle"
  7 #define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
  8 #define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]
  9
 10 @interface RouteAnnotation : BMKPointAnnotation
 11 {
 12     int _type; ///<0:起点 1:终点 2:公交 3:地铁 4:驾乘 5:途经点
 13     int _degree;
 14 }
 15
 16 @property (nonatomic) int type;
 17 @property (nonatomic) int degree;
 18 @end
 19
 20 @implementation RouteAnnotation
 21
 22 @synthesize type = _type;
 23 @synthesize degree = _degree;
 24 @end
 25
 26 @interface ServerRepairViewController () <BMKMapViewDelegate, BMKRouteSearchDelegate>
 27 {
 28     BMKRouteSearch* _routesearch;
 29     BMKMapView *_mapView;
 30     UILabel *_distanceLab;
 31 }
 32
 33 @end
 34
 35 @implementation ServerRepairViewController
 36
 37 - (void)viewDidLoad {
 38     [super viewDidLoad];
 39
 40     self.title = @"外出服务";
 41 //    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"驾车" style:UIBarButtonItemStylePlain target:self action:@selector(driveSearchAction)];
 42
 43     _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 0, K_ScreenWidth, K_ScreenHeight - 64)];
 44     [self.view addSubview:_mapView];
 45     _routesearch = [[BMKRouteSearch alloc] init];
 46
 47     _mapView.delegate = self;
 48     _routesearch.delegate = self;
 49
 50     _distanceLab = [[UILabel alloc] initWithFrame:CGRectMake(0, K_ScreenHeight - 64 - 40, K_ScreenWidth, 40)];
 51     _distanceLab.backgroundColor = [UIColor whiteColor];
 52     _distanceLab.textColor = [UIColor blueColor];
 53     [self.view addSubview:_distanceLab];
 54
 55
 56     // 计算两点之间直线距离
 57 //    CLLocationDistance  distance = BMKMetersBetweenMapPoints(BMKMapPointMake(self.startCoor.latitude, self.startCoor.longitude), BMKMapPointMake(self.endCoor.latitude, self.endCoor.longitude));
 58
 59 }
 60
 61
 62
 63 - (void)viewWillAppear:(BOOL)animated
 64 {
 65     [_mapView viewWillAppear];
 66
 67     _mapView.delegate = self;
 68     _routesearch.delegate = self;
 69
 70     [self driveSearchAction];
 71 }
 72
 73 - (void)viewWillDisappear:(BOOL)animated
 74 {
 75
 76     [_mapView viewWillDisappear];
 77     _mapView.delegate = nil;
 78     _routesearch.delegate = nil;
 79 }
 80
 81 -(void)dealloc
 82 {
 83     if (_mapView != nil) {
 84         _mapView = nil;
 85     }
 86     if (_routesearch != nil) {
 87         _routesearch = nil;
 88     }
 89 }
 90
 91
 92 - (void)driveSearchAction
 93 {
 94 //    NSLog(@"1 = %lf, %lf, %lf, %lf",self.startCoor.latitude, self.startCoor.longitude, self.endCoor.latitude, self.endCoor.longitude);
 95
 96     BMKPlanNode *start = [[BMKPlanNode alloc] init];
 97     start.pt = self.startCoor;
 98
 99     BMKPlanNode *end = [[BMKPlanNode alloc] init];
100     end.pt = self.endCoor;
101     end.name = self.addrName;
102
103     BMKDrivingRoutePlanOption *drivingRoutePlanOption = [[BMKDrivingRoutePlanOption alloc] init];
104     drivingRoutePlanOption.from = start;
105     drivingRoutePlanOption.to = end;
106
107     BOOL flag = [_routesearch drivingSearch:drivingRoutePlanOption];
108     if (flag) {
109         NSLog(@"car检索发送成功");
110     } else {
111         NSLog(@"car检索发送失败");
112     }
113 }
114
115
116 #pragma mark - BMKMapViewDelegate
117
118 - (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
119 {
120     if ([annotation isKindOfClass:[RouteAnnotation class]]) {
121         return [self getRouteAnnotationView:view viewForAnnotation:(RouteAnnotation*)annotation];
122     }
123     return nil;
124 }
125
126 - (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay
127 {
128     if ([overlay isKindOfClass:[BMKPolyline class]]) {
129         BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
130         polylineView.fillColor = [[UIColor alloc] initWithRed:0 green:1 blue:1 alpha:1];
131         polylineView.strokeColor = [[UIColor alloc] initWithRed:0 green:0 blue:1 alpha:0.7];
132         polylineView.lineWidth = 3.0;
133         return polylineView;
134     }
135     return nil;
136 }
137
138
139 #pragma mark - BMKRouteSearchDelegate
140
141 - (void)onGetDrivingRouteResult:(BMKRouteSearch*)searcher result:(BMKDrivingRouteResult*)result errorCode:(BMKSearchErrorCode)error
142 {
143     NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
144     [_mapView removeAnnotations:array];
145     array = [NSArray arrayWithArray:_mapView.overlays];
146     [_mapView removeOverlays:array];
147
148     if (error == BMK_SEARCH_NO_ERROR) {
149         BMKDrivingRouteLine* plan = (BMKDrivingRouteLine*)[result.routes objectAtIndex:0];
150         _distanceLab.text = [NSString stringWithFormat:@"总路线:%.2lf公里", plan.distance * 2 / 1000.0];
151         // 计算路线方案中的路段数目
152         NSInteger size = [plan.steps count];
153         int planPointCounts = 0;
154         for (int i = 0; i < size; i++) {
155             BMKDrivingStep* transitStep = [plan.steps objectAtIndex:i];
156             if(i==0){
157                 RouteAnnotation* item = [[RouteAnnotation alloc]init];
158                 item.coordinate = plan.starting.location;
159                 item.title = @"起点";
160                 item.type = 0;
161                 [_mapView addAnnotation:item]; // 添加起点标注
162
163             }else if(i==size-1){
164                 RouteAnnotation* item = [[RouteAnnotation alloc]init];
165                 item.coordinate = plan.terminal.location;
166                 item.title = @"终点";
167                 item.type = 1;
168                 [_mapView addAnnotation:item]; // 添加起点标注
169             }
170             //添加annotation节点
171             RouteAnnotation* item = [[RouteAnnotation alloc]init];
172             item.coordinate = transitStep.entrace.location;
173             item.title = transitStep.entraceInstruction;
174             item.degree = transitStep.direction * 30;
175             item.type = 4;
176             [_mapView addAnnotation:item];
177
178             //轨迹点总数累计
179             planPointCounts += transitStep.pointsCount;
180         }
181         // 添加途经点
182         if (plan.wayPoints) {
183             for (BMKPlanNode* tempNode in plan.wayPoints) {
184                 RouteAnnotation* item = [[RouteAnnotation alloc]init];
185                 item = [[RouteAnnotation alloc]init];
186                 item.coordinate = tempNode.pt;
187                 item.type = 5;
188                 item.title = tempNode.name;
189                 [_mapView addAnnotation:item];
190             }
191         }
192         //轨迹点
193         BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
194         int i = 0;
195         for (int j = 0; j < size; j++) {
196             BMKDrivingStep* transitStep = [plan.steps objectAtIndex:j];
197             int k=0;
198             for(k=0;k<transitStep.pointsCount;k++) {
199                 temppoints[i].x = transitStep.points[k].x;
200                 temppoints[i].y = transitStep.points[k].y;
201                 i++;
202             }
203
204         }
205         // 通过points构建BMKPolyline
206         BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
207         [_mapView addOverlay:polyLine]; // 添加路线overlay
208         delete []temppoints;
209         [self mapViewFitPolyLine:polyLine];
210     }
211 }
212
213
214 #pragma mark - 私有
215 - (NSString*)getMyBundlePath1:(NSString *)filename
216 {
217     NSBundle * libBundle = MYBUNDLE ;
218     if ( libBundle && filename ){
219         NSString * s=[[libBundle resourcePath ] stringByAppendingPathComponent : filename];
220         return s;
221     }
222     return nil ;
223 }
224
225 - (BMKAnnotationView*)getRouteAnnotationView:(BMKMapView *)mapview viewForAnnotation:(RouteAnnotation*)routeAnnotation
226 {
227     BMKAnnotationView* view = nil;
228     switch (routeAnnotation.type) {
229         case 0:
230         {
231             view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"start_node"];
232             if (view == nil) {
233                 view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"start_node"];
234                 view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_start.png"]];
235                 view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
236                 view.canShowCallout = TRUE;
237             }
238             view.annotation = routeAnnotation;
239         }
240             break;
241         case 1:
242         {
243             view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"end_node"];
244             if (view == nil) {
245                 view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"end_node"];
246                 view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_end.png"]];
247                 view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
248                 view.canShowCallout = TRUE;
249             }
250             view.annotation = routeAnnotation;
251         }
252             break;
253         case 2:
254         {
255             view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"bus_node"];
256             if (view == nil) {
257                 view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"bus_node"];
258                 view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_bus.png"]];
259                 view.canShowCallout = TRUE;
260             }
261             view.annotation = routeAnnotation;
262         }
263             break;
264         case 3:
265         {
266             view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"rail_node"];
267             if (view == nil) {
268                 view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"rail_node"];
269                 view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_rail.png"]];
270                 view.canShowCallout = TRUE;
271             }
272             view.annotation = routeAnnotation;
273         }
274             break;
275         case 4:
276         {
277             view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"route_node"];
278             if (view == nil) {
279                 view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"route_node"];
280                 view.canShowCallout = TRUE;
281             } else {
282                 [view setNeedsDisplay];
283             }
284
285             UIImage* image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_direction.png"]];
286             view.image = [image imageRotatedByDegrees:routeAnnotation.degree];
287             view.annotation = routeAnnotation;
288
289         }
290             break;
291         case 5:
292         {
293             view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"waypoint_node"];
294             if (view == nil) {
295                 view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"waypoint_node"];
296                 view.canShowCallout = TRUE;
297             } else {
298                 [view setNeedsDisplay];
299             }
300
301             UIImage* image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_waypoint.png"]];
302             view.image = [image imageRotatedByDegrees:routeAnnotation.degree];
303             view.annotation = routeAnnotation;
304         }
305             break;
306         default:
307             break;
308     }
309
310     return view;
311 }
312
313
314 //根据polyline设置地图范围
315 - (void)mapViewFitPolyLine:(BMKPolyline *) polyLine {
316     CGFloat ltX, ltY, rbX, rbY;
317     if (polyLine.pointCount < 1) {
318         return;
319     }
320     BMKMapPoint pt = polyLine.points[0];
321     ltX = pt.x, ltY = pt.y;
322     rbX = pt.x, rbY = pt.y;
323     for (int i = 1; i < polyLine.pointCount; i++) {
324         BMKMapPoint pt = polyLine.points[i];
325         if (pt.x < ltX) {
326             ltX = pt.x;
327         }
328         if (pt.x > rbX) {
329             rbX = pt.x;
330         }
331         if (pt.y > ltY) {
332             ltY = pt.y;
333         }
334         if (pt.y < rbY) {
335             rbY = pt.y;
336         }
337     }
338     BMKMapRect rect;
339     rect.origin = BMKMapPointMake(ltX , ltY);
340     rect.size = BMKMapSizeMake(rbX - ltX, rbY - ltY);
341     [_mapView setVisibleMapRect:rect];
342     _mapView.zoomLevel = _mapView.zoomLevel - 0.3;
343 }
344 @end
时间: 2024-08-02 16:47:19

随记(九)--确定两个地点的经纬度,自制驾车路线并计算其距离的相关文章

Java对关于两个地点的根据经纬度算出后排序

/** * 查询收货地址列表 * * @param request * @param wechatId * @return */ @RequestMapping("/weixin/address/queryRecentlyAddress") public AddressVo queryRecentlyAddress(HttpServletRequest request, Integer wechatId, AddressVo vo) { String openId = OauthUti

php通过两个地点经纬度求距离

<?php /** *求两个已知经纬度之间的距离,单位为米 *@param lng1,lng2 经度 *@param lat1,lat2 纬度 *@return float 距离,单位米 *@author yalong sun<[email protected]> **/ function getdistance($lng1,$lat1,$lng2,$lat2){ //将角度转为狐度 $radLat1=deg2rad($lat1);//deg2rad()函数将角度转换为弧度 $radLa

通过地图上两个点的经纬度测算两点的距离

根据两点经纬度计算距离 这些经纬线是怎样定出来的呢?地球是在不停地绕地轴旋转(地轴是一根通过地球南北两极和地球中心的 假想线),在地球中腰画一个与地轴垂直的大圆圈,使圈上的每一点都和南北两极的距离相等,这个圆圈 就叫作"赤道".在赤道的南北两边,画出许多和赤道平行的圆圈,就是"纬圈":构成这些圆圈的线段, 叫做纬线.我们把赤道定为纬度零度,向南向北各为90度,在赤道以南的叫南纬,在赤道以北的叫北纬. 北极就是北纬90度,南极就是南纬90度.纬度的高低也标志着气候的冷

根据地图上的两个点各自的x,y坐标,计算出2点之间的直线距离。显示为公里、米

/** * calc_map_distance() , 根据地图上的两个点各自的x,y坐标,计算出2点之间的直线距离 * @param array $point_1 第1个点的x,y坐标 array( 101 , 202 ) * @param array $point_2 第2个点的x,y坐标 array( 101 , 202 ) * @param bool $calc_as_string 是否计算为字符串公里距离 , 如果未否返回数字 * @return float | false | str

百度地图地点搜索和鼠标点击地点获取经纬度

百度地图地点搜索和鼠标点击地点获取经纬度,这些都是地图比较基本 效果图:如下 代码部分: <!DOCTYPE html><html>    <head>    <meta charset="utf-8">    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

GPS获取Location 获取所在地点的经纬度

利用手机获取所在地点的经纬度: Location 在Android 开发中还是经常用到的,比如 通过经纬度获取天气,根据Location 获取所在地区详细Address (比如Google Map 开发).等.而在Android 中通过LocationManager 来获取Location .通常获取Location 有GPS 获取,WIFI 获取. 如下介绍GPS获取Location: 第一步: 创建一个Android 工程命名为GPS 第二步: 在MainActivity中利用Locatio

根据百度地图API获取指定地点的经纬度

做项目时,遇到对地点获取地图中对应的经纬度,作一下笔记,以备以后直接使用 package com.hpzx.data; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.n

两个常见位操作面试题 不用加减乘除运算符计算两数之和及a b 3

分享一下我老师大神的人工智能教程吧.零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!http://www.captainbed.net <两个常见位操作面试题不用加减乘除运算符计算两数之和及a=b*3> 地址:http://blog.csdn.net/morewindows/article/details/8710737转载请标明出处,谢谢. 欢迎关注微博:http://weibo.com/MoreWindows 上一篇<位操作基础篇之位操作全面总结>

在现有xp系统下安装win7系统记(需两块硬盘操作)

问题: 1.用户现有系统为xp系统,3个有数据内容的分区.在现有基础上加win7系统 答: 思路: 1.在PE下利用DiskGenius工具将D盘划分出两个分区D.G,将win7镜像还原到G分区. 2.用修复工具easyBCD修复系统引导. easyBCD不支持在xp下运行 在PE下取消现有XP活动分区,隐藏C盘,将G提升主分区,设成活动分区. 修复引导,还是不行. 最后:用同样大小的盘,将win7分区克隆到新硬盘C分区,xp克隆到D分区. 修复系统引导. 在win7下装easyBCD修改启动项