1

我在使用 Google Directions API 时遇到问题。我正在获取 JSON 字符串并对其进行解析,得到 overview_polylines 字符串

NSString *allPolylines = [NSString stringWithFormat:[[[routes objectAtIndex:0] objectForKey:@"overview_polyline"] objectForKey:@"points"]];

这东西行得通。我无法将其添加到地图中。我正在使用这篇文章http://iosguy.com/tag/directions-api/这似乎正是我所追求的。

我已经实施了

-(NSMutableArray *)decodePolyLine:(NSString *)encodedStr

方法,效果很好。我对结果进行了 NSLogged,它显示出来好像我正在输出 CLLocation 对象。

问题是我不能让它显示在地图上。这是下面的代码

    NSMutableArray *_path = [self decodePolyLine:allPolylines];
    NSInteger numberOfSteps = _path.count;

    CLLocationCoordinate2D coordinates[numberOfSteps];
    for (NSInteger index = 0; index < numberOfSteps; index++) {
        CLLocation *location = [_path objectAtIndex:index];
        CLLocationCoordinate2D coordinate = location.coordinate;

        coordinates[index] = coordinate;
    }

    MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
    [_mapView addOverlay:polyLine];
    [self mapView:_mapView viewForOverlay:polyLine];

我还尝试添加显式调用

[self mapView:_mapView viewForOverlay:polyLine];

这是:

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {
    MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
    polylineView.strokeColor = [UIColor redColor];
    polylineView.lineWidth = 1.0;

    return polylineView;
}

最后一个方法被调用,我使用 NSLog 进行了检查,但地图上没有显示任何内容。

有什么想法吗?提前致谢!

4

1 回答 1

1

The code shown looks OK except that you're not supposed to call viewForOverlay directly.

The map view will call that delegate method when it needs to show the overlay.

The simplest reason it would not be calling the delegate method is that the map view's delegate property is not set.

If the delegate property is set, then verify that the coordinates are what you're expecting and also make sure they are not flipped (latitude in longitude and vice versa).

Another thing to check:
If _mapView is an IBOutlet, make sure it is actually connected to the map view in the xib.

于 2012-05-30T12:27:34.527 回答