Draw a MKPolyline on a MapView shows straight line between both locations - ios

How to get location like google maps which shows exact paths between locations. As it shows direct straight line which does not contain any path between both places and neither shows location around them through which it passes.
I have used following code:
CLLocationCoordinate2D coordinateArray[2];
coordinateArray[0] = CLLocationCoordinate2DMake(51.5074, 0.1278);
coordinateArray[1] = CLLocationCoordinate2DMake(48.8566, 2.3522);
self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray count:2];
[self.mapView setVisibleMapRect:[self.routeLine boundingMapRect]]; //If you want the route to be visible
[self.mapView addOverlay:self.routeLine];
For connection of both the paths this code have been implemented.
-(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;
}

Try my code one:
- (void)drawRouteFromLocation:(LocationPin *)source toLocation:(LocationPin *)destination
{
[self removeCurrentRouteDrawing];
MKPlacemark *sourcePlaceMark = [[MKPlacemark alloc]initWithCoordinate:source.actualCoordinate addressDictionary:nil];
MKPlacemark *destinationPlaceMark = [[MKPlacemark alloc]initWithCoordinate:destination.actualCoordinate addressDictionary:nil];
MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
request.source = [[MKMapItem alloc] initWithPlacemark:sourcePlaceMark];
request.destination = [[MKMapItem alloc] initWithPlacemark:destinationPlaceMark];
request.requestsAlternateRoutes = NO;
MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
[directions calculateDirectionsWithCompletionHandler:
^(MKDirectionsResponse *response, NSError *error) {
if (error)
{
// Handle Error
}
else
{
[self showRoute:response];
}
}];
}
-(void)showRoute:(MKDirectionsResponse *)response
{
for (MKRoute *route in response.routes)
{
[self.mkMapView addOverlay:route.polyline level:MKOverlayLevelAboveRoads];
// for (MKRouteStep *step in route.steps)
// {
// DEBUG_LOG(#"%#", step.instructions);
// }
}
}
#pragma mark - MKMapViewDelegate
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
// DEBUG_LOG(#"region Will Change");
if ([self.delegate respondsToSelector:#selector(mapView:regionWillChangeAnimated:)])
{
[self.delegate mapView:mapView regionWillChangeAnimated:animated];
}
}
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
// DEBUG_LOG(#"region Did Change");
if ([self.delegate respondsToSelector:#selector(mapView:regionDidChangeAnimated:)])
{
[self.delegate mapView:mapView regionDidChangeAnimated:animated];
}
}
- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView
{
DEBUG_LOG(#"mapView Did Finish Loading Map");
self.mapInitialized = YES;
if ([self.delegate respondsToSelector:#selector(mapViewDidFinishLoadingMap:)])
{
[self.delegate mapViewDidFinishLoadingMap:mapView];
}
}
//- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
//{
// if ([overlay isKindOfClass: [MKPolyline class]])
// {
// // This is for a dummy overlay to work around a problem with overlays
// // not getting removed by the map view even though we asked for it to
// // be removed.
// MKOverlayView * dummyView = [[MKOverlayView alloc] init];
// dummyView.alpha = 0.0;
// return dummyView;
// }
// else
// {
// return nil;
// }
//}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
if ([self.delegate respondsToSelector:#selector(mapView:viewForAnnotation:)])
{
return [self.delegate mapView:mapView viewForAnnotation:annotation];
}
return nil;
}
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id < MKOverlay >)overlay
{
if ([overlay isKindOfClass:[MKPolyline class]])
{
MKPolylineRenderer *renderer = [[ MKPolylineRenderer alloc]initWithOverlay:overlay];
renderer.lineWidth = 10;
renderer.strokeColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
[self _zoomToPolyLine:self.mkMapView polyLine:overlay animated:YES];
return renderer;
}
else
{
return nil;
}
}
#pragma mark - Utils
-(void)_zoomToPolyLine:(MKMapView*)map polyLine:(MKPolyline*)polyLine animated:(BOOL)animated
{
// MKPolygon* polygon =
// [MKPolygon polygonWithPoints:polyLine.points count:polyLine.pointCount];
//
// [self.mkMapView setRegion:MKCoordinateRegionForMapRect([polygon boundingMapRect])
// animated:animated];
[map setVisibleMapRect:[polyLine boundingMapRect] edgePadding:UIEdgeInsetsMake(35.0, 35.0, 35.0, 35.0) animated:animated];
}
- (void)removeCurrentRouteDrawing
{
if (self.mkMapView.overlays.count)
{
[self.mkMapView removeOverlays:self.mkMapView.overlays];
}
}

Related

How do I access the available data when I click an annotation?

I have several annotation points. What I want to do is when I click an annotation point I want to display that data. I have a custom Annotation class with a title and an NSDictionary. The dictionary contains an image URL and ID. I want to fetch these when I click on a specific annotation.
EDIT: I know about the didSelectAnnotation, but how do I access the data?
-(void)annotations{
CLLocationCoordinate2D pinPoint;
for (NSDictionary * dict in _dataArray) {
pinPoint.latitude =[[dict valueForKey:#"lat"] doubleValue];
pinPoint.longitude = [[dict valueForKey:#"lng"] doubleValue];
_myAnnotation = [[MapViewAnnotation alloc]initWithTitle:[dict valueForKey:#"name"]andCoordinate:pinPoint andData:dict];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:pinPoint addressDictionary:nil] ;
_destination = [[MKMapItem alloc] initWithPlacemark:placemark];
_myAnnotation.title=[dict valueForKey:#"name"];
[self.mapKit addAnnotation:_myAnnotation];
}
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
[self.mapKit setRegion:[self.mapKit regionThatFits:region] animated:YES];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(MapViewAnnotation*)annotation
{
// If it's the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
// Handle any custom annotations.
if ([annotation isKindOfClass:[MapViewAnnotation class]])
{
// Try to dequeue an existing pin view first.
MKAnnotationView *pinView = (MKAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:#"CustomPinAnnotationView"];
if (!pinView)
{
// If an existing pin view was not available, create one.
pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"CustomPinAnnotationView"];
pinView.canShowCallout = YES;
NSLog(#"%#",[annotation.data valueForKey:#"name"]);
pinView.image = [UIImage imageNamed:#"image"];
pinView.calloutOffset = CGPointMake(0, 32);
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
pinView.rightCalloutAccessoryView = rightButton;
} else {
pinView.annotation = annotation;
}
return pinView;
}
return nil;
}
-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
[request setTransportType:MKDirectionsTransportTypeWalking];
request.source = [MKMapItem mapItemForCurrentLocation];
request.destination = _destination;
request.requestsAlternateRoutes = NO;
MKDirections *directions =
[[MKDirections alloc] initWithRequest:request];
[directions calculateDirectionsWithCompletionHandler:
^(MKDirectionsResponse *response, NSError *error) {
if (error) {
// Handle Error
} else {
[self showRoute:response];
}
}];
}
EDIT 2nd :
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
MapViewAnnotation * annotation = (MapViewAnnotation *) view;
NSLog(#"%#",[annotation.data valueForKey:#"name"]);
NSURL *url =[NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:#"SPOTTD_profilePic"]];
NSData *imageData = [NSData dataWithContentsOfURL:url];
_imgMyProfile.image = [UIImage imageWithData:imageData];
}
You can use the didSelectAnnotationView method, in combination with the annotation property of the MKAnnotationView:
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
if ([view.annotation isKindOfClass:[MapViewAnnotation class]]) {
MapViewAnnotation *annotation = (MapViewAnnotation)view.annotation;
}
}
After you have safely cast the annotation to your custom type, you can access its properties like the NSDictionary.
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
NSString *latPoint2 = [NSString stringWithFormat:#"%.6f", view.annotation.coordinate.latitude];
NSString *longPoint2 =[NSString stringWithFormat:#"%.6f", view.annotation.coordinate.longitude];
There is one more method for annotation which is
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{}.In this method you can show your data on click of annotation.Hope this will help you. If any query let me know. Thanks

Selected map pins show the same coordinate

I am trying get the coordinate of each pin I select on my map. Pins are the local search results that users search on the map. I have an issue that every pin I select it give me the same value. Can anyone help me with this please? Thanks in advance.
- (IBAction)searchAction:(id)sender {
[sender resignFirstResponder];
[self.mapView removeAnnotations:[self.mapView annotations]];
[self performSearch]; }
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
// If it's the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
MKPinAnnotationView *mypin = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:#"current"];
//mypin.pinColor = MKPinAnnotationColorPurple;
mypin.backgroundColor = [UIColor clearColor];
UIButton *goToDetail = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
mypin.rightCalloutAccessoryView = goToDetail;
mypin.draggable = NO;
mypin.highlighted = YES;
mypin.animatesDrop = TRUE;
mypin.canShowCallout = YES;
return mypin;
}
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
MKPointAnnotation *annotation = view.annotation;
self.tappedCoord = annotation.coordinate;
// Longs are the same for every pin I select
NSLog(#"%f", [[view annotation] coordinate].longitude);
}
- (void)performSearch {
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = _searchText.text;
request.region = _mapView.region;
self.matchingItems = [[NSMutableArray alloc] init];
MKLocalSearch *search = [[MKLocalSearch alloc]initWithRequest:request];
[search startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
if (response.mapItems.count == 0)
NSLog(#"No Matches");
else
for (MKMapItem *item in response.mapItems)
{
[self.matchingItems addObject:item];
MKPointAnnotation *annotation = [[MKPointAnnotation alloc]init];
annotation.coordinate = item.placemark.coordinate;
annotation.title = item.name;
annotation.subtitle = [NSString stringWithFormat:#"%#, %# %#",
item.placemark.addressDictionary[#"Street"],
item.placemark.addressDictionary[#"State"],
item.placemark.addressDictionary[#"ZIP"]];
//NSLog(#"%#", item.placemark.addressDictionary);
[_mapView addAnnotation:annotation];
}
}];
}

MKDirections not showing route on map in iOS

I am working on one app, I need to show route directions between two coordinates. I have used MKDirections and have passed two coordinates as source and destination, however on mapView its not showing any route or drawing any polyline. Below is my code. In MKDirections its always showing nil. Please let me know what I am doing wrong.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.activityIndicator.hidden = YES;
self.routeDetailsButton.hidden = YES;
self.routeDetailsButton.enabled = NO;
self.mapView.delegate = self;
self.mapView.showsUserLocation = YES;
self.navigationItem.title = #"RouteMaster";
}
#pragma mark - MapKit delegate methods
- (void)mapView:(MKMapView *)aMapView didUpdateUserLocation:(MKUserLocation *)userLocation {
CLLocationCoordinate2D loc = [userLocation.location coordinate];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 1000.0f, 1000.0f);
[self.mapView setRegion:region animated:YES];
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
- (IBAction)handleRoutePressed:(id)sender {
// We're working
CLLocationCoordinate2D sourceCoords = CLLocationCoordinate2DMake(28.6100, 77.2300);
MKPlacemark *sourcePlacemark = [[MKPlacemark alloc] initWithCoordinate:sourceCoords addressDictionary:nil];
MKMapItem *srcMapItem = [[MKMapItem alloc]initWithPlacemark:sourcePlacemark];
CLLocationCoordinate2D destinationCoords = CLLocationCoordinate2DMake(18.9750, 72.8258);
MKPlacemark *destinationPlacemark = [[MKPlacemark alloc] initWithCoordinate:destinationCoords addressDictionary:nil];
MKMapItem *distMapItem = [[MKMapItem alloc]initWithPlacemark:destinationPlacemark];
MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
[request setSource:srcMapItem];
[request setDestination:distMapItem];
MKDirections *direction = [[MKDirections alloc]initWithRequest:request];
[direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
if (error)
NSLog(#"Error %#", error.description);
else
NSLog(#"response = %#",response);
NSArray *arrRoutes = [response routes];
[arrRoutes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
MKRoute *rout = obj;
MKPolyline *line = [rout polyline];
[self.mapView addOverlay:line];
NSLog(#"Rout Name : %#",rout.name);
NSLog(#"Total Distance (in Meters) :%f",rout.distance);
NSArray *steps = [rout steps];
NSLog(#"Total Steps : %lu",(unsigned long)[steps count]);
[steps enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"Rout Instruction : %#",[obj instructions]);
NSLog(#"Rout Distance : %f",[obj distance]);
}];
}];
}];
}
#pragma mark - Utility Methods
- (void)plotRouteOnMap:(MKRoute *)route
{
if(_routeOverlay) {
[self.mapView removeOverlay:_routeOverlay];
}
// Update the ivar
_routeOverlay = route.polyline;
// Add it to the map
[self.mapView addOverlay:_routeOverlay];
}
#pragma mark - MKMapViewDelegate methods
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
renderer.strokeColor = [UIColor redColor];
renderer.lineWidth = 4.0;
return renderer;
}
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id)overlay {
if ([overlay isKindOfClass:[MKPolyline class]]) {
MKPolylineView* aView = [[MKPolylineView alloc]initWithPolyline:(MKPolyline*)overlay] ;
aView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.5];
aView.lineWidth = 10;
return aView;
}
return nil;
}
Mostly this error occur if [_mapView setRegion:region] area and polyline route path are not on same region(both should need to display on same screen).
In my case I was searching for USA route path while my region was India. So it wont call to -(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id)overlay; function.
add this method
-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
MKPolylineRenderer * routeLineRenderer = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
routeLineRenderer.strokeColor = [UIColor blueColor];
routeLineRenderer.lineWidth = 4;
return routeLineRenderer;
}

display route on iOS 7 maps: addOverlay has no effect

i want display a point to point route inside my mapView, i use this code for create the route:
- (IBAction)backToYourCar {
MKPlacemark *sourcePlacemark = [[MKPlacemark alloc] initWithCoordinate:self.annotationForCar.coordinate addressDictionary:nil];
NSLog(#"coordiante : locationIniziale %f", sourcePlacemark.coordinate.latitude);
MKMapItem *carPosition = [[MKMapItem alloc] initWithPlacemark:sourcePlacemark];
MKMapItem *actualPosition = [MKMapItem mapItemForCurrentLocation];
NSLog(#"coordiante : source %f, ActualPosition %f", carPosition.placemark.coordinate.latitude ,actualPosition.placemark.coordinate.latitude);
MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
request.source = actualPosition;
request.destination = carPosition;
request.requestsAlternateRoutes = YES;
MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
[directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
if (error) {
NSLog(#"Error : %#", error);
}
else {
[self showDirections:response]; //response is provided by the CompletionHandler
}
}];
}
and this for show the route on the map:
- (void)showDirections:(MKDirectionsResponse *)response
{
for (MKRoute *route in response.routes) {
[self.mapView addOverlay:route.polyline level:MKOverlayLevelAboveRoads];
}
}
actually this code does nothing.
if i try to print the the distance of route i get the correct value:
route distance: 1910.000000
then the route is right, but i can't understand why it doesn't appear on the map!
Any suggestions?
after a day of research i have solved with this 3 steps:
Set the delegate (self.mapView.delegate = self).
import the MKMapViewDelegate
Implemente the new iOS7 MapView delegate method:
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay(id<MKOverlay>)overlay:
this is my implementation:
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
if ([overlay isKindOfClass:[MKPolyline class]]) {
MKPolyline *route = overlay;
MKPolylineRenderer *routeRenderer = [[MKPolylineRenderer alloc] initWithPolyline:route];
routeRenderer.strokeColor = [UIColor blueColor];
return routeRenderer;
}
else return nil;
}
this method is automatically called by the delegate when you add the polyline on the map.

mapView and UITable detail

trying to pass my annotation's data (name, address, phone #, url, description, etc) to a DetailViewController with a table. stuck----please read the code. the data isnt passed with calloutAccessoryTapped. Help?
- (IBAction)gasButton:(id)sender {
[self.mapView removeAnnotations:self.mapView.annotations];
self.localSearchRequest = [[MKLocalSearchRequest alloc] init];
self.localSearchRequest.region = self.mapView.region;
self.localSearchRequest.naturalLanguageQuery = #"gas station";
self.localSearch = [[MKLocalSearch alloc] initWithRequest:self.localSearchRequest];
[self.localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
if(error){
NSLog(#"localSearch startWithCompletionHandlerFailed! Error: %#", error);
return;
} else {
for(mapItem in response.mapItems){
MKPointAnnotation *zip = [[MKPointAnnotation alloc] init ];
zip.coordinate = mapItem.placemark.location.coordinate;
zip.title = mapItem.name;
self.mapView.delegate = self;
[self.mapView addAnnotation: zip];
[self.mapView selectAnnotation:zip animated:YES];
[self.mapView setUserTrackingMode:MKUserTrackingModeFollow];
NSLog(#"%# - 1", mapItem.name);
CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:zip.coordinate.latitude longitude:zip.coordinate.longitude];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude];
CLLocationDistance distance = [loc1 distanceFromLocation:loc2];
NSString *dist = [[NSString alloc] initWithFormat:#"%.2f miles", distance * 0.000621371192];
zip.subtitle = dist;
}
}
}];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
MKPinAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"MYVC"];
if ([annotation isKindOfClass:[MKUserLocation class]])
{
return nil;
}
else if ([annotation isKindOfClass: [MKPointAnnotation class] ])
{
annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
annotationView.enabled = YES;
annotationView.animatesDrop = YES;
annotationView.pinColor = MKPinAnnotationColorGreen;
annotationView.canShowCallout = YES;
NSLog(#"%# - 2", mapItem.name);
return annotationView;
}
return nil;
}
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
NSLog(#"%# - tapped", mapItem.name);
//STUCK HERE - mapItem.name is (null)
}
mapItem exists in the for loop of your gasButton function, no where else as far as I can see. You've created an annotation (zip) and added it to your map. In viewForAnnotation you are given that annotation as a parameter and asked to make an annotationView from it. In calloutAccessoryControlTapped you are given an annotationView and told it has been tapped. You need to follow the chain back to your data. From the annotationView get the annotation and from the annotation get your name.
MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
NSLog(#"%# - tapped", view.annotation.title);
}

Resources