Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Frameworks needed </p> <p>QuartzCore.framework<br> CoreLocation.framework<br> MapKit.framework</p> <p>Files Needed</p> <p>JSONKit.h<br> JSONKit.m</p> <p>Set -fno-objc-arc in compile source for JSON in case of ARC.</p> <p>In header File </p> <pre><code>__block IBOutlet MKMapView *__mapView; NSArray* routes; MKPointAnnotation *startLocation; MKPointAnnotation *endLocation; MKPolyline *polyLine; </code></pre> <p>Implementation piece of code...</p> <pre><code>- (void)viewDidLoad { // [__mapView setShowsUserLocation:YES]; [__mapView setZoomEnabled:YES]; [__mapView setScrollEnabled:YES]; [__mapView setMapType:MKMapTypeStandard]; [__mapView setDelegate:self]; routes=[[NSArray alloc] init]; [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (IBAction)drawPath:(id)sender { dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){ //Background Thread [self showRouteFrom:startLocation to:endLocation]; dispatch_async(dispatch_get_main_queue(), ^(void){ //Run UI Updates if (polyLine) { [__mapView setVisibleMapRect:[polyLine boundingMapRect]]; [__mapView addOverlay:polyLine]; [self centerMap]; } NSLog(@"drawing path completed"); }); }); } -(void) showRouteFrom: (id&lt;MKAnnotation&gt;)source to:(id&lt;MKAnnotation&gt;)destination; { if(routes) { [__mapView removeAnnotations:[__mapView annotations]]; } [__mapView addAnnotation:source]; [__mapView addAnnotation:destination]; NSLog(@"source title is %@",source.title); NSLog(@"destination title is %@",destination.title); routes = [self calculateRoutesFrom:source.coordinate to:destination.coordinate]; NSLog(@"routes are %@",routes); NSInteger numberOfSteps = routes.count; CLLocationCoordinate2D coordinates[numberOfSteps]; for (NSInteger index = 0; index &lt; numberOfSteps; index++) { CLLocation *location = [routes objectAtIndex:index]; CLLocationCoordinate2D coordinate = location.coordinate; coordinates[index] = coordinate; } polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps]; NSLog(@"poly line to be added as ovelay is %@",polyLine); } -(NSArray*) calculateRoutesFrom:(CLLocationCoordinate2D) f to: (CLLocationCoordinate2D) t { NSString* saddr = [NSString stringWithFormat:@"%f,%f", f.latitude, f.longitude]; NSString* daddr = [NSString stringWithFormat:@"%f,%f", t.latitude, t.longitude]; NSString* apiUrlStr = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&amp;destination=%@&amp;sensor=false&amp;avoid=highways&amp;mode=",saddr,daddr]; NSLog(@"Fired API %@",apiUrlStr); NSURL* apiUrl = [NSURL URLWithString:apiUrlStr]; NSError* error = nil; NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&amp;error]; NSDictionary *dic=[apiResponse objectFromJSONString]; if (dic!=nil) { NSArray *routPoints=[[NSArray alloc] initWithArray:[dic valueForKey:@"routes"]]; NSDictionary *polylineOverview=[[routPoints objectAtIndex:0] valueForKey:@"overview_polyline"]; NSString *polylinePoints = [polylineOverview objectForKey:@"points"]; return [self decodePolyLine:[polylinePoints mutableCopy]]; } return nil; } - (NSMutableArray *)decodePolyLine: (NSMutableString *)encoded { [encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\" options:NSLiteralSearch range:NSMakeRange(0, [encoded length])]; NSInteger len = [encoded length]; NSInteger index = 0; NSMutableArray *array = [[NSMutableArray alloc] init]; NSInteger lat=0; NSInteger lng=0; while (index &lt; len) { NSInteger b; NSInteger shift = 0; NSInteger result = 0; do { b = [encoded characterAtIndex:index++] - 63; result |= (b &amp; 0x1f) &lt;&lt; shift; shift += 5; } while (b &gt;= 0x20); NSInteger dlat = ((result &amp; 1) ? ~(result &gt;&gt; 1) : (result &gt;&gt; 1)); lat += dlat; shift = 0; result = 0; do { b = [encoded characterAtIndex:index++] - 63; result |= (b &amp; 0x1f) &lt;&lt; shift; shift += 5; } while (b &gt;= 0x20); NSInteger dlng = ((result &amp; 1) ? ~(result &gt;&gt; 1) : (result &gt;&gt; 1)); lng += dlng; NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5]; NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5]; //printf("[%f,", [latitude doubleValue]); //printf("%f]", [longitude doubleValue]); CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]]; [array addObject:loc]; } return array; } #pragma mark- MKMapView delegate method - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id &lt;MKOverlay&gt;)overlay { MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay]; polylineView.strokeColor = [UIColor purpleColor]; polylineView.lineWidth = 5.0; NSLog(@"polyline in viewFor overlay: %@",polylineView); return polylineView; } - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation { NSLog(@"did update user location called "); MKCoordinateRegion region; region.span.latitudeDelta = .005; region.span.longitudeDelta = .005; region.center = userLocation.coordinate; [mapView setRegion:region animated:YES]; } -(void) centerMap { MKCoordinateRegion region; CLLocationDegrees maxLat = -90.0; CLLocationDegrees maxLon = -180.0; CLLocationDegrees minLat = 90.0; CLLocationDegrees minLon = 180.0; for(int idx = 0; idx &lt; routes.count; idx++) { CLLocation* currentLocation = [routes objectAtIndex:idx]; if(currentLocation.coordinate.latitude &gt; maxLat) maxLat = currentLocation.coordinate.latitude; if(currentLocation.coordinate.latitude &lt; minLat) minLat = currentLocation.coordinate.latitude; if(currentLocation.coordinate.longitude &gt; maxLon) maxLon = currentLocation.coordinate.longitude; if(currentLocation.coordinate.longitude &lt; minLon) minLon = currentLocation.coordinate.longitude; } region.center.latitude = (maxLat + minLat) / 2.0; region.center.longitude = (maxLon + minLon) / 2.0; region.span.latitudeDelta = 0.01; region.span.longitudeDelta = 0.01; region.span.latitudeDelta = ((maxLat - minLat)&lt;0.0)?100.0:(maxLat - minLat); region.span.longitudeDelta = ((maxLon - minLon)&lt;0.0)?100.0:(maxLon - minLon); [__mapView setRegion:region animated:YES]; } #pragma mark- UITextField delegate method - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { [self.view bringSubviewToFront:textField]; CGRect rect=textField.frame; [[NSUserDefaults standardUserDefaults] setValue:NSStringFromCGRect(rect) forKey:@"textFieldRect"]; rect.origin.y=self.view.frame.size.height-260; [UIView animateWithDuration:0.3 animations:^{ [textField setFrame:rect]; }]; return YES; } - (BOOL)textFieldShouldReturn:(UITextField *)textField { NSString *rectStr=[[NSUserDefaults standardUserDefaults] valueForKey:@"textFieldRect"]; NSArray *rectArray=[rectStr componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"{,} "]]; CGRect rect; rect.origin.x=[[rectArray objectAtIndex:2] floatValue]; rect.origin.y=[[rectArray objectAtIndex:4] floatValue]; rect.size.width=[[rectArray objectAtIndex:8] floatValue]; rect.size.height=[[rectArray objectAtIndex:10] floatValue]; [UIView animateWithDuration:0.3 animations:^{ [textField setFrame:rect]; }]; [textField resignFirstResponder]; return YES; } - (void)textFieldDidEndEditing:(UITextField *)textField { NSDictionary *locationDic=[self getLatLongOfPlace:[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]]; NSDictionary *latLongDic=[[[[[locationDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"geometry"]valueForKey:@"viewport"] valueForKey:@"northeast"]; if (textField.tag==0) { startLocation=[[MKPointAnnotation alloc] init]; [startLocation setCoordinate:CLLocationCoordinate2DMake([[latLongDic valueForKey:@"lat"] floatValue], [[latLongDic valueForKey:@"lng"] floatValue])]; startLocation.title=[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; }else{ endLocation=[[MKPointAnnotation alloc] init]; [endLocation setCoordinate:CLLocationCoordinate2DMake([[latLongDic valueForKey:@"lat"] floatValue], [[latLongDic valueForKey:@"lng"] floatValue])]; endLocation.title=[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; } NSLog(@"object at index is viewport %@",[[[[[locationDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"geometry"]valueForKey:@"viewport"] valueForKey:@"northeast"]); } #pragma mark Getting lat long from place name. -(NSDictionary*)getLatLongOfPlace:(NSString*)place { NSString* apiUrlStr = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?address=%@&amp;sensor=true",place]; NSLog(@"Fired URL:- %@",apiUrlStr); NSURL* apiUrl = [NSURL URLWithString:apiUrlStr]; NSError* error = nil; NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&amp;error]; NSDictionary *dic=[apiResponse objectFromJSONString]; return dic; } </code></pre> <p>Here is <a href="https://dl.dropboxusercontent.com/u/75870052/DrawRoute.zip" rel="noreferrer">SampleCode</a> I made</p> <p><strong>NOTE:---</strong> <strong>In case if sample doesn't work for u jsut this line in viewDidLoad Method</strong></p> <p>// [__mapView setShowsUserLocation:YES];</p> <p>Screenshot </p> <p><img src="https://i.stack.imgur.com/aEySF.png" alt="enter image description here"></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload