-1

i have question regarding ios map application. I didn't found any good help for some point. I tried both ios and google map but i am unable to find the help for both. I am stuck on few points so can any one help me those points are

  1. how to show route b/w two points either in ios or google map
  2. after show route how to update the route if user move to that location
  3. how to get the distance and time b/w two point for bike,car,walking etc either in ios or google map
  4. how to get the coordinate just by address
  5. is there any option for step by step navigation either for ios or google map
Saxon Druce
  • 17,406
  • 5
  • 50
  • 71
preciouslogic
  • 65
  • 2
  • 7

2 Answers2

2

I will give you a start point to make this - to write a route and get directions

Get directions method (google directions api):

- (void)callAPIGetDirection:(NSString *)mode
{
// Start new request
CLLocationCoordinate2D currentLocation = [(RCAppDelegate *)[[UIApplication sharedApplication] delegate]getCurrentLocation];

// NSString *urlString = [NSString stringWithFormat:kAPIGetDirection, currentLocation.latitude, currentLocation.longitude, self.location.latitude, self.location.longitude];

//urlString = @"http://bizannouncements.com/Vega/services/app/getDirections.php?origlat=43.653310&origlong=-79.38277000000001&destlat=43.66361000000001&destlong=-79.35547000000001";
 NSString *urlString = @"";
if(![mode isEqualToString:@"transit"])
{
    urlString =[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=true&mode=%@", currentLocation.latitude, currentLocation.longitude, self.location.latitude, self.location.longitude, mode];
}
else
{
    urlString =[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=true&mode=%@&departure_time=%ld", currentLocation.latitude, currentLocation.longitude, self.location.latitude, self.location.longitude, mode, (long)[[NSDate date] timeIntervalSince1970] + 1800];
}

[MBProgressHUD showHUDAddedTo:self.view animated:YES];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSDictionary *rO = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
    NSLog(@"%@", rO);
    if(![[rO objectForKey:@"status"] isEqualToString:@"INVALID_REQUEST"] && ![[rO objectForKey:@"status"] isEqualToString:@"ZERO_RESULTS"])
    {


        //OVER_QUERY_LIMIT

        if(![[rO objectForKey:@"status"] isEqualToString:@"OVER_QUERY_LIMIT"])
        {
            NSArray *routes = [rO objectForKey:@"routes"];


            NSArray *legs = [routes[0] objectForKey:@"legs"];
            //NSLog(@"legs %@", legs[0]);
            NSArray *steps = [legs[0] objectForKey:@"steps"];
            //NSLog(@"steps : %@", steps);

            Place* office = [[Place alloc] init];
            office.name = self.location.name;
            office.description = @"";
            office.latitude = [[[legs[0] objectForKey:@"end_location"] objectForKey:@"lat"] doubleValue];
            office.longitude = [[[legs[0] objectForKey:@"end_location"] objectForKey:@"lng"] doubleValue];

            //NSLog(@"office: %f", office.latitude);

            NSMutableArray *routing = [[NSMutableArray alloc] init];

            [_instructions removeAllObjects];
            int ii = 1;
            for(NSDictionary *step in steps)
            {
                [_instructions addObject:[NSString stringWithFormat:@"%i: %@", ii, [step objectForKey:@"html_instructions"]]];
                NSDictionary *suStep = [step objectForKey:@"end_location"];
                CLLocation *loc = [[CLLocation alloc] initWithLatitude:[[suStep objectForKey:@"lat"] doubleValue] longitude:[[suStep objectForKey:@"lng"] doubleValue]];
                [routing addObject:loc];
                ii++;

            }
            [_table reloadData];

            //self.mainMap.routes = routing;

            //[self.mainMap showRouteTo:office];
        }
        else
        {
            [RCCommonUtils showMessageWithTitle:@"Error" andContent:@"Directions service is down. Please try again a bit later!"];

        }

    }
    else
    {
        [RCCommonUtils showMessageWithTitle:@"Error" andContent:@"There are no directions available!"];

    }




    [MBProgressHUD hideHUDForView:self.view animated:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    [RCCommonUtils showMessageWithTitle:@"Error" andContent:@"Network error. Please try again later!"];
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}];

[operation start];


}

Draw path on a map:

 - (id) initWithFrame:(CGRect) frame
 {
self = [super initWithFrame:frame];
if (self != nil) {
    mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    mapView.showsUserLocation = YES;
    [mapView setDelegate:self];
    [self addSubview:mapView];
    routeView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, mapView.frame.size.width, mapView.frame.size.height)];
    routeView.userInteractionEnabled = NO;
    [mapView addSubview:routeView];

    self.lineColor = [UIColor colorWithWhite:0.2 alpha:1.0];
}
return self;
 }

 -(void) centerMap {
MKCoordinateRegion region;

CLLocationDegrees maxLat = -90;
CLLocationDegrees maxLon = -180;
CLLocationDegrees minLat = 90;
CLLocationDegrees minLon = 180;
for(int idx = 0; idx < self.routes.count; idx++)
{
    CLLocation* currentLocation = [self.routes objectAtIndex:idx];
    if(currentLocation.coordinate.latitude > maxLat)
        maxLat = currentLocation.coordinate.latitude;
    if(currentLocation.coordinate.latitude < minLat)
        minLat = currentLocation.coordinate.latitude;
    if(currentLocation.coordinate.longitude > maxLon)
        maxLon = currentLocation.coordinate.longitude;
    if(currentLocation.coordinate.longitude < minLon)
        minLon = currentLocation.coordinate.longitude;
}
region.center.latitude     = (maxLat + minLat) / 2;
region.center.longitude    = (maxLon + minLon) / 2;
region.span.latitudeDelta  = maxLat - minLat;
region.span.longitudeDelta = maxLon - minLon;

[mapView setRegion:region animated:YES];
}

-(void) showRouteTo:(Place*)t {

if(self.routes) {
    [mapView removeAnnotations:[mapView annotations]];
}

PlaceMark* to = [[PlaceMark alloc] initWithPlace:t];
[mapView addAnnotation:to];

[self updateRouteView];
[self centerMap];
}

-(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, 4.0);

for(int i = 0; i < self.routes.count; i++) {
    CLLocation* location = [self.routes objectAtIndex:i];
    CGPoint point = [mapView convertCoordinate:location.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);

}
nerowolfe
  • 4,787
  • 3
  • 20
  • 19
0

Get Coordinate by address

- (CLLocationCoordinate2D) geoCodeUsingAddress: (NSString *) address
{
   CLLocationCoordinate2D myLocation;

   // — modified from the stackoverflow page – we use the SBJson parser instead of the string scanner –

   NSString *esc_addr = [address stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
   NSString *req = [NSString stringWithFormat: @"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];
   NSDictionary *googleResponse = [[NSString stringWithContentsOfURL: [NSURL URLWithString: req] encoding: NSUTF8StringEncoding error: NULL] JSONValue];

   NSDictionary *resultsDict = [googleResponse valueForKey:  @"results"];   // get the results dictionary
   NSDictionary *geometryDict = [   resultsDict valueForKey: @"geometry"];   // geometry dictionary within the  results dictionary
   NSDictionary *locationDict = [  geometryDict valueForKey: @"location"];   // location dictionary within the geometry dictionary

   // nslo (@”– returning latitude & longitude from google –”);

   NSArray *latArray = [locationDict valueForKey: @"lat"]; NSString *latString = [latArray lastObject];     // (one element) array entries provided by the json parser
   NSArray *lngArray = [locationDict valueForKey: @"lng"]; NSString *lngString = [lngArray lastObject];     // (one element) array entries provided by the json parser

   myLocation.latitude = [latString doubleValue];     // the json parser uses NSArrays which don’t support “doubleValue”
   myLocation.longitude = [lngString doubleValue];

   return myLocation;
}
Tarek Hallak
  • 18,422
  • 7
  • 59
  • 68