Có thể hiển thị tuyến đường trong MapKit: Chỉ cần sử dụng MKPolyline
tôi nhận được chuỗi polyline từ googleMapsApi. Tôi phân tích nó trên máy chủ với php, và trả lại chuỗi polilyne cuối cùng cho ứng dụng của tôi.
NSMutableArray *points = [myApp decodePolyline:[route objectForKey:@"polyline"]];
if([points count] == 0)
{
return;
}
// while we create the route points, we will also be calculating the bounding box of our route
// so we can easily zoom in on it.
MKMapPoint northEastPoint;
MKMapPoint southWestPoint;
// create a c array of points.
MKMapPoint* pointArr = malloc(sizeof(CLLocationCoordinate2D) * [points count]);
for(int idx = 0; idx < points.count; idx++)
{
// break the string down even further to latitude and longitude fields.
NSString* currentPointString = [points objectAtIndex:idx];
NSArray* latLonArr = [currentPointString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];
CLLocationDegrees latitude = [[latLonArr objectAtIndex:0] doubleValue];
CLLocationDegrees longitude = [[latLonArr objectAtIndex:1] doubleValue];
// create our coordinate and add it to the correct spot in the array
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
MKMapPoint point = MKMapPointForCoordinate(coordinate);
if (idx == 0) {
northEastPoint = point;
southWestPoint = point;
}
else
{
if (point.x > northEastPoint.x)
northEastPoint.x = point.x;
if(point.y > northEastPoint.y)
northEastPoint.y = point.y;
if (point.x < southWestPoint.x)
southWestPoint.x = point.x;
if (point.y < southWestPoint.y)
southWestPoint.y = point.y;
}
pointArr[idx] = point;
_currentLenght++;
}
// create the polyline based on the array of points.
self.routeLine = [MKPolyline polylineWithPoints:pointArr count:points.count];
_routeRect = MKMapRectMake(southWestPoint.x, southWestPoint.y,
northEastPoint.x - southWestPoint.x,
northEastPoint.y - southWestPoint.y);
// clear the memory allocated earlier for the points
free(pointArr);
if (nil != self.routeLine) {
[self.mapView addOverlay:self.routeLine];
}
[self.mapView setVisibleMapRect:_routeRect];
Và hiển thị:
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
MKOverlayView* overlayView = nil;
if(overlay == self.routeLine)
{
self.routeLineView = [[[MKPolylineView alloc] initWithPolyline:self.routeLine] autorelease];
self.routeLineView.fillColor = [UIColor blueColor];
self.routeLineView.strokeColor = TICNavigatorColor;
self.routeLineView.lineWidth = 7;
self.routeLineView.lineJoin = kCGLineJoinRound;
self.routeLineView.lineCap = kCGLineCapRound;
overlayView = self.routeLineView;
}
return overlayView;
}
Hãy thử.
có dự án ví dụ nào không? –
Dự án Trình xem KML sẽ giúp bạn vẽ tuyến đường giữa hai địa điểm. – iGo