[英]How to connect 2 annotations with a coloured line inside a MKMapView?
如何在Mkmapview内部用彩色线条连接2条注释?
可以使用google direction API。通过起点和终点位置
//http://maps.googleapis.com/maps/api/directions/jsonorigin=origin_place&destination=destination_place&waypoints=Charlestown,MA|Lexington,MA&sensor=false
它将给出您具有解析和提取坐标的jSON响应。 与那条线
self.routeLine = [MKPolyline polylineWithPoints:arrPoints count:routeArray.count];
在这里在.h文件中创建创建对象routeView作为UIImageView
类,还创建lineColor作为UIColor
类,例如bellow
UIImageView* routeView;
UIColor* lineColor;
在viewDidLoad:
方法之后,编写此代码。
routeView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, mapView.frame.size.width, mapView.frame.size.height)];
routeView.userInteractionEnabled = NO;
lineColor = [UIColor magentaColor];
[mapView addSubview:routeView];
然后在您要画线时更新。还有routes
是NSMutableArray
,我们在其中存储CLLocation
(纬度长)
-(void) updateRouteView
{
CGContextRef context = CGBitmapContextCreate(nil,
routeView.frame.size.width,
routeView.frame.size.height,
8,
4 * routeView.frame.size.width,
CGColorSpaceCreateDeviceRGB(),
kCGImageAlphaPremultipliedLast);
CGContextSetStrokeColorWithColor(context, lineColor.CGColor);
CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);
CGContextSetLineWidth(context, 3.0);
for(int i = 0; i < routes.count; i++)
{
CLLocation* location1 = [routes objectAtIndex:i];
CGPoint point = [mapView convertCoordinate:location1.coordinate toPointToView:routeView];
if(i == 0)
{
CGContextMoveToPoint(context, point.x, routeView.frame.size.height - point.y);
}
else
{
CGContextAddLineToPoint(context, point.x, routeView.frame.size.height - point.y);
}
}
CGContextStrokePath(context);
CGImageRef image = CGBitmapContextCreateImage(context);
UIImage* img = [UIImage imageWithCGImage:image];
routeView.image = img;
CGContextRelease(context);
}
另请参阅此链接iphone如何在mapkit上的两点之间画线
在我看来,这看起来很复杂。 我在网上找到了另一个解决方案。 我首先必须将叠加层添加到mapView的地方
CLLocationCoordinate2D coordinateArray[2];
coordinateArray[0] = start_location;
coordinateArray[1] = end_location;
self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray count:2];
/***********************************************/
[_mapView addOverlay:self.routeLine];
然后,将viewcontroller设置为mkmapviewdelegate并实现委托方法:
-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay{
if(overlay == self.routeLine)
{
if(nil == self.routeLineView)
{
self.routeLineView = [[MKPolylineView alloc] initWithPolyline:self.routeLine];
self.routeLineView.fillColor = [UIColor redColor];
self.routeLineView.strokeColor = [UIColor redColor];
self.routeLineView.lineWidth = 5;
}
return self.routeLineView;
}
return nil;}
但是它仍然没有显示,我在做什么错?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.