现在的位置: 首页 > 综合 > 正文

mapkit 中有关两地点距离计算

2013年04月08日 ⁄ 综合 ⁄ 共 1663字 ⁄ 字号 评论关闭

用mapkit进行地图的开发,经常要用到的就是计算两个地点间的距离问题,方法很简单:

 

    CLLocationManager * locmanager = [[CLLocationManager alloc]init];//先定义一个cllocationmanager的实例

 

  [locmanager setDelegate:self]; //设置代理为本身

  [locmanager setDesiredAccuracy:kCLLocationAccuracyBest];//设置精确度为最准确

  [locmanager startUpdatingLocation];//更新 location

 

 

    //定义一个新的cllocation实例,下面会取得user location 和这个新的地点间的距离

    CLLocation * newLocation = [[CLLocation alloc]initWithLatitude:32.0206410 longitude:118.7889040];

 

    //为了方便查看,在这两个地点都添加标记,加到mapView中。

 

    MapAnnotation * fuzimiaoAnnotation = [[MapAnnotation alloc]init];

    fuzimiaoAnnotation.annotationType = myMapAnnotationTypeApple;

    fuzimiaoAnnotation.title = @"Fu Zi Miao";

    fuzimiaoAnnotation.coordinate = newLocation.coordinate;

 

    MapAnnotation * newAnnotation = [[MapAnnotation alloc]init];

    newAnnotation.title = @"You Current Location!";

    newAnnotation.annotationType = myMapAnnotationTypeApple;

    newAnnotation.coordinate = self.myCurrentLocation;

 

 

    [self.locationMapView addAnnotation:newAnnotation];

    [self.locationMapView selectAnnotation:newAnnotation animated:YES];

    [self.locationMapView addAnnotation:fuzimiaoAnnotation];

    [self.locationMapView selectAnnotation:fuzimiaoAnnotation animated:YES];

 

    NSLog(@"%@",[NSString stringWithFormat:@"%0.2f km",[[locmanager location] distanceFromLocation:newLocation]/1000]);


  //关键就在这里,取得两个cllocation间的距离,单位是m

    CLLocationDistance newDistance = [[locmanager location] distanceFromLocation:newLocation];

 

    //下面是设置mapView的显示区域,使得这两个地点都能出现在地图中,这里就用到了刚算出来的距离。

    [self.locationMapView setRegion:MKCoordinateRegionMakeWithDistance(self.myCurrentLocation, newDistance, newDistance) animated:YES];


 

    [newLocation release];

    [fuzimiaoAnnotation release];

    [newAnnotation release];

 

 

抱歉!评论已关闭.