Iphone 在多个位置之间绘制地图路径
我是iphone开发的新手,我想在5个位置之间画一条路径,如何在谷歌地图中画出路径。 我想要从位置1到位置2、位置2到位置3、位置3到位置4以及位置4到位置5的路径 这是我的密码Iphone 在多个位置之间绘制地图路径,iphone,ipad,ios6.1,Iphone,Ipad,Ios6.1,我是iphone开发的新手,我想在5个位置之间画一条路径,如何在谷歌地图中画出路径。 我想要从位置1到位置2、位置2到位置3、位置3到位置4以及位置4到位置5的路径 这是我的密码 - (void)viewDidLoad { [super viewDidLoad]; NSDictionary *d1,*d2,*d3,*d4,*d5; d1=[NSDictionary dictionaryWithObjectsAndKeys:@"location1",@"comments",@"1",@"id"
- (void)viewDidLoad {
[super viewDidLoad];
NSDictionary *d1,*d2,*d3,*d4,*d5;
d1=[NSDictionary dictionaryWithObjectsAndKeys:@"location1",@"comments",@"1",@"id",@"23.02941395",@"latitude",@"72.54620655",@"longitude",nil];
d2=[NSDictionary dictionaryWithObjectsAndKeys:@"location2",@"comments",@"2",@"id",@"23.028359049999995",@"latitude",@"72.54537318333334",@"longitude",nil];
d3=[NSDictionary dictionaryWithObjectsAndKeys:@"location3",@"comments",@"3",@"id",@"23.029545",@"latitude",@"72.546036",@"longitude",nil];
d4=[NSDictionary dictionaryWithObjectsAndKeys:@"location4",@"comments",@"4",@"id",@"23.030050",@"latitude",@"72.546226",@"longitude",nil];
d5=[NSDictionary dictionaryWithObjectsAndKeys:@"location5",@"comments",@"5",@"id",@"23.030050",@"latitude",@"72.546022",@"longitude",nil];
self.reports=[NSArray arrayWithObjects:d1,d2,d3,d4,d5,nil];
for (NSDictionary *d in self.reports) {
float latitude=[[d valueForKey:@"latitude"] floatValue];
float longitude=[[d valueForKey:@"longitude"] floatValue];
Place* home = [[[Place alloc] init] autorelease];
home.name = [d valueForKey:@"comments"];
home.latitude = latitude;
home.longitude = longitude;
PlaceMark *from = [[[PlaceMark alloc] initWithPlace:home] autorelease];
[mapView addAnnotation:from];
}
[self centerMap];
}
-(void) centerMap
{
MKCoordinateRegion region;
CLLocationDegrees maxLat = -90;
CLLocationDegrees maxLon = -180;
CLLocationDegrees minLat = 120;
CLLocationDegrees minLon = 150;
NSMutableArray *temp=[NSArray arrayWithArray:self.reports];
NSLog(@"%@",temp);
for (int i=0; i<[temp count];i++) {
Place* home = [[[Place alloc] init] autorelease];
home.latitude = [[[temp objectAtIndex:i] valueForKey:@"latitude"]floatValue];
home.longitude =[[[temp objectAtIndex:i] valueForKey:@"longitude"]floatValue];
PlaceMark* from = [[[PlaceMark alloc] initWithPlace:home] autorelease];
CLLocation* currentLocation = (CLLocation*)from ;
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];
}
- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
if (annotation == mapView.userLocation)
return nil;
MKPinAnnotationView *pin = (MKPinAnnotationView *) [mapView dequeueReusableAnnotationViewWithIdentifier: @"asdf"];
if (pin == nil)
pin = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier: @"asdf"] autorelease];
else
pin.annotation = annotation;
pin.userInteractionEnabled = YES;
UIButton *disclosureButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[disclosureButton setFrame:CGRectMake(0, 0, 30, 30)];
pin.rightCalloutAccessoryView = disclosureButton;
pin.pinColor = MKPinAnnotationColorRed;
//pin.animatesDrop = YES;
[pin setEnabled:YES];
[pin setCanShowCallout:YES];
return pin;
}
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
NSString *strTitle = [NSString stringWithFormat:@"%@",[view.annotation title]];
NSMutableDictionary *d;
NSMutableArray *temp=[NSArray arrayWithArray:self.reports];
for (int i = 0; i<[temp count]; i++)
{
d = (NSMutableDictionary*)[temp objectAtIndex:i];
NSString *strAddress = [NSString stringWithFormat:@"%@",[d valueForKey:@"comments"]];
if([strAddress isEqualToString:strTitle]) {
[self presentModalViewController:self.nxtDetailsVCtr animated:YES];
[self.nxtDetailsVCtr.lblDetail setText:strAddress];
break;
}
}
}
-(void)viewDidLoad{
[超级视图下载];
NSD字典*d1、*d2、*d3、*d4、*d5;
d1=[NSDictionary Dictionary With Objects SandKeys:@“location1”,“comments”,“1”,“id”,“23.02941395”,“latitude”,“72.54620655”,“经度”,零];
d2=[NSDictionary Dictionary With Objects SandKeys:“location2”,“comments”,“2”,“id”,“23.0283590499995”,“latitude”,“72.54537318333334”,“经度”,零];
d3=[NSDictionary Dictionary With Objects SandKeys:“location3”,“comments”,“3”,“id”,“23.029545”,“latitude”,“72.546036”,“经度”,零];
d4=[NSDictionary Dictionary With Objects SandKeys:@“location4”、@“comments”、@“4”、@“id”、@“23.030050”、@“latitude”、@“72.546226”、@“latitude”,无];
d5=[NSDictionary Dictionary WithObjectsAndKeys:@“location5”,“comments”,“5”,“id”,“23.030050”,“latitude”,“72.546022”,“经度”,零];
self.reports=[NSArray数组,其中包含对象:d1、d2、d3、d4、d5、nil];
for(self.reports中的NSDictionary*d){
浮动纬度=[[d valueForKey:@“纬度”]floatValue];
浮动经度=[[d valueForKey:@“经度”]floatValue];
Place*home=[[Place alloc]init]autorelease];
home.name=[d valueForKey:@“comments”];
home.latitude=纬度;
home.longitude=经度;
PlaceMark*from=[[PlaceMark alloc]initWithPlace:home]自动释放];
[地图视图添加注释:从];
}
[自我中心地图];
}
-(无效)中心地图
{
协调区域;
CLLocationDegrees maxLat=-90;
CLLocationDegrees maxLon=-180;
CLLocationDegrees minLat=120;
CLLocationDegrees minLon=150;
NSMUTABLEARRY*temp=[NSArray arrayWithArray:self.reports];
NSLog(@“%@”,温度);
对于(int i=0;i maxLat)
maxLat=currentLocation.coordinate.latitude;
if(currentLocation.coordinate.latitudemaxLon)
maxLon=当前位置.坐标.经度;
if(currentLocation.coordinate.longitude 对于(int i=0;i您可以使用nvplonelineannotation
在地图内部绘制线。以下是所需的框架
QuartzCore.framework
CoreLocation.framework
MapKit.framework
需要的文件
JSONKit.h
JSONKit.m
在arc的情况下,在JSON的编译源代码中设置-fno objc arc
在头文件中
__block IBOutlet MKMapView *__mapView;
NSArray* routes;
MKPointAnnotation *startLocation;
MKPointAnnotation *endLocation;
MKPolyline *polyLine;
实现一段代码
- (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<MKAnnotation>)source to:(id<MKAnnotation>)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 < 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=%@&destination=%@&sensor=false&avoid=highways&mode=",saddr,daddr];
NSLog(@"Fired API %@",apiUrlStr);
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSError* error = nil;
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&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 < len)
{
NSInteger b;
NSInteger shift = 0;
NSInteger result = 0;
do
{
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do
{
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 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 <MKOverlay>)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 < routes.count; idx++)
{
CLLocation* currentLocation = [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.0;
region.center.longitude = (maxLon + minLon) / 2.0;
region.span.latitudeDelta = 0.01;
region.span.longitudeDelta = 0.01;
region.span.latitudeDelta = ((maxLat - minLat)<0.0)?100.0:(maxLat - minLat);
region.span.longitudeDelta = ((maxLon - minLon)<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=%@&sensor=true",place];
NSLog(@"Fired URL:- %@",apiUrlStr);
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSError* error = nil;
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&error];
NSDictionary *dic=[apiResponse objectFromJSONString];
return dic;
}
-(void)viewDidLoad
{
//[_地图视图设置显示位置:是];
[_地图视图设置缩放启用:是];
[_地图视图设置可克隆:是];
[_mapView setMapType:MKMapTypeStandard];
[\uu mapView setDelegate:self];
routes=[[NSArray alloc]init];
[超级视图下载];
//加载视图后,通常从nib执行任何其他设置。
}
-(iAction)绘图路径:(id)发送方{
调度异步(调度获取全局队列(调度队列优先级默认为0),^(无效){
//背景线程
[自显示路线从:惊人位置到:结束位置];
dispatch\u async(dispatch\u get\u main\u queue(),^(void){
//运行UI更新
if(多段线){
[_地图视图集VisibleMaprect:[多段线边界MapRect]];
[_地图视图添加覆盖:多段线];
[自我中心地图];
}
NSLog(@“绘制路径已完成”);
});
});
}
-(void)showRouteFrom:(id)源到:(id)目的地;
{
如果(路线)
{
[\u地图视图删除注释:[\u地图视图注释]];
}
[\u地图视图添加注释:源];
[\u地图视图添加注释:目的地];
NSLog(@“源标题为%@”,source.title);
NSLog(@“目的地标题为%@”,destination.title);
routes=[self-CalculatorOutesFrom:source.coordinate to:destination.coordinate];
NSLog(@“路由为%@”,路由);
NSInteger numberOfSteps=routes.count;
CLLocationCoordinate2D坐标[步数];
for(NSInteger索引=0;indexNSMutableArray *polyLineArray;
-(void) showRouteFrom: (id<MKAnnotation>)source to:(id<MKAnnotation>)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 < numberOfSteps; index++)
{
CLLocation *location = [routes objectAtIndex:index];
CLLocationCoordinate2D coordinate = location.coordinate;
coordinates[index] = coordinate;
}
polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
[polyLineArray addObject:polyLine];
// NSLog(@"poly line to be added as ovelay is %@",polyLine);
}
- (IBAction)drawMultiple:(id)sender
{
polyLineArray=[[NSMutableArray alloc] init];
NSDictionary *kolkata,*delhi,*chennai,*mumbai,*pune;
kolkata=[NSDictionary dictionaryWithObjectsAndKeys:@"location1",@"comments",@"1",@"id",@"23.0083321",@"latitude",@"88.54276659999",@"longitude",nil];
delhi=[NSDictionary dictionaryWithObjectsAndKeys:@"location2",@"comments",@"2",@"id",@"28.889816",@"latitude",@"77.3418147",@"longitude",nil];
chennai=[NSDictionary dictionaryWithObjectsAndKeys:@"location3",@"comments",@"3",@"id",@"13.23339843",@"latitude",@"80.3322912",@"longitude",nil];
mumbai=[NSDictionary dictionaryWithObjectsAndKeys:@"location4",@"comments",@"4",@"id",@"19.2716339",@"latitude",@"72.9864994",@"longitude",nil];
pune=[NSDictionary dictionaryWithObjectsAndKeys:@"location5",@"comments",@"5",@"id",@"18.6346965",@"latitude",@"73.9894867",@"longitude",nil];
NSArray *arrayOfLocations=[[NSArray alloc] initWithObjects:kolkata,delhi,chennai,mumbai,pune,nil];
MKPointAnnotation *start=[[MKPointAnnotation alloc] init];
MKPointAnnotation *end=[[MKPointAnnotation alloc] init];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread
for (int i=0;i<arrayOfLocations.count-1;i++)
{
NSDictionary *dic=[arrayOfLocations objectAtIndex:i];
[start setCoordinate:CLLocationCoordinate2DMake([[dic valueForKey:@"latitude"] floatValue], [[dic valueForKey:@"longitude"] floatValue])];
dic=[arrayOfLocations objectAtIndex:i+1];
[end setCoordinate:CLLocationCoordinate2DMake([[dic valueForKey:@"latitude"] floatValue], [[dic valueForKey:@"longitude"] floatValue])];
[self showRouteFrom:start to:end];
}
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
NSDictionary *tempDic=[[NSDictionary alloc] initWithDictionary:[arrayOfLocations objectAtIndex:0]];
[start setCoordinate:CLLocationCoordinate2DMake([[tempDic valueForKey:@"latitude"] floatValue], [[tempDic valueForKey:@"longitude"] floatValue])];
[__mapView addAnnotation:start];
[__mapView addAnnotation:end];
if (polyLine) {
[__mapView setVisibleMapRect:[polyLine boundingMapRect]];
for (MKPolyline *pLine in polyLineArray) {
[__mapView addOverlay:pLine];
}
}
NSLog(@"drawing path completed");
});
});
}
#import "ViewController.h"
#import "JSONKit.h"
@interface ViewController ()
@end
@implementation ViewController
NSMutableArray *locationarry ;
NSMutableDictionary * citywiselatlong ;
- (void)viewDidLoad
{
locationarry = [[NSMutableArray alloc]initWithObjects:@"Ahmedabad",@"Rajkot",@"Baroda",@"Surat", nil];
citywiselatlong = [[NSMutableDictionary alloc]init];
[self locationfind];
NSMutableString* TotalXMLString = [[NSMutableString alloc]init];
[TotalXMLString appendFormat:@"http://maps.googleapis.com/maps/api/distancematrix/json?origins="];
[TotalXMLString appendFormat:@"%@,%@&destinations=",[[citywiselatlong valueForKey:[locationarry objectAtIndex:0]] valueForKey:@"lat"] ,[[citywiselatlong valueForKey:[locationarry objectAtIndex:0]] valueForKey:@"lng"]];
for (int i = 1; i < [locationarry count]; i++) {
[TotalXMLString appendFormat:@"%@,%@",[[citywiselatlong valueForKey:[locationarry objectAtIndex:i]] valueForKey:@"lat"] ,[[citywiselatlong valueForKey:[locationarry objectAtIndex:i]] valueForKey:@"lng"]];
if (i != [locationarry count] -1 ) {
[TotalXMLString appendFormat:@"|"];
}
else
{
[TotalXMLString appendFormat:@"&mode=driving&sensor=false"];
}
}
NSURL* apiUrl = [NSURL URLWithString:[TotalXMLString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
NSError* error = nil;
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&error];
NSDictionary *dic=[apiResponse objectFromJSONString];
NSLog(@"%@",dic);
NSMutableArray * distance = [[NSMutableArray alloc]initWithArray:[[[[dic valueForKey:@"rows"] objectAtIndex:0] valueForKey:@"elements"]valueForKey:@"distance"]];
for (int j= 0 ; j < [distance count]; j++) {
NSMutableDictionary *data = [[NSMutableDictionary alloc]initWithDictionary:[distance objectAtIndex:j]];
}
NSLog(@"%@",distance);
[__mapView setShowsUserLocation:YES];
[__mapView setZoomEnabled:YES];
[__mapView setScrollEnabled:YES];
[__mapView setMapType:MKMapTypeHybrid];
[__mapView setDelegate:self];
routes=[[NSArray alloc] init];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark- MKMapView delegate method
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)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];
}
- (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 < len)
{
NSInteger b;
NSInteger shift = 0;
NSInteger result = 0;
do
{
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do
{
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 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;
}
-(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=%@&destination=%@&sensor=false&avoid=highways&mode=",saddr,daddr];
NSLog(@"Fired API %@",apiUrlStr);
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSError* error = nil;
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&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;
}
- (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];
}
NSLog(@"drawing path completed");
});
});
}
-(void) showRouteFrom: (id<MKAnnotation>)source to:(id<MKAnnotation>)destination;
{
routes = [self calculateRoutesFrom:source.coordinate to:destination.coordinate];
NSLog(@"routes are %@",routes);
NSInteger numberOfSteps = routes.count;
CLLocationCoordinate2D coordinates[numberOfSteps];
for (NSInteger index = 0; index < numberOfSteps; index++)
{
CLLocation *location = [routes objectAtIndex:index];
CLLocationCoordinate2D coordinate = location.coordinate;
coordinates[index] = coordinate;
}
polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
[polyLineArray addObject:polyLine];
}
- (IBAction)drawMultiple:(id)sender
{
polyLineArray=[[NSMutableArray alloc] init];
MKPointAnnotation *start=[[MKPointAnnotation alloc] init];
MKPointAnnotation *end=[[MKPointAnnotation alloc] init];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread
for (int i=0;i<locationarry.count-1;i++)
{
NSArray *part = [[NSArray alloc]initWithArray:[[locationarry objectAtIndex:i] componentsSeparatedByString:@","]];
NSDictionary *dic=[citywiselatlong objectForKey:[part objectAtIndex:0]];
[start setCoordinate:CLLocationCoordinate2DMake([[dic valueForKey:@"lat"] floatValue], [[dic valueForKey:@"lng"] floatValue])];
part = [[NSArray alloc]initWithArray:[[locationarry objectAtIndex:i +1 ] componentsSeparatedByString:@","]];
dic=[citywiselatlong objectForKey:[part objectAtIndex:0]];
[end setCoordinate:CLLocationCoordinate2DMake([[dic valueForKey:@"lat"] floatValue], [[dic valueForKey:@"lng"] floatValue])];
[self showRouteFrom:start to:end];
}
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
NSArray *part = [[NSArray alloc]initWithArray:[[locationarry objectAtIndex:0] componentsSeparatedByString:@","]];
NSDictionary *tempDic=[[NSDictionary alloc] initWithDictionary:[citywiselatlong objectForKey:[part objectAtIndex:0]]];
[start setCoordinate:CLLocationCoordinate2DMake([[tempDic valueForKey:@"lat"] floatValue], [[tempDic valueForKey:@"lng"] floatValue])];
if (polyLine) {
[__mapView setVisibleMapRect:[polyLine boundingMapRect]];
for (MKPolyline *pLine in polyLineArray) {
[__mapView addOverlay:pLine];
}
}
for (int i =0 ; i< [locationarry count]; i ++)
{
NSArray *part = [[NSArray alloc]initWithArray:[[locationarry objectAtIndex:i] componentsSeparatedByString:@","]];
NSDictionary *dic=[citywiselatlong objectForKey:[part objectAtIndex:0]];
MKPointAnnotation *first=[[MKPointAnnotation alloc] init];
MKPointAnnotation *second=[[MKPointAnnotation alloc] init];
[first setCoordinate:CLLocationCoordinate2DMake([[dic valueForKey:@"lat"] floatValue], [[dic valueForKey:@"lng"] floatValue])];
if(i+1<[locationarry count])
{
NSArray *part = [[NSArray alloc]initWithArray:[[locationarry objectAtIndex:i + 1] componentsSeparatedByString:@","]];
dic=[citywiselatlong objectForKey:[part objectAtIndex:0]];
[second setCoordinate:CLLocationCoordinate2DMake([[dic valueForKey:@"lat"] floatValue], [[dic valueForKey:@"lng"] floatValue])];
}
else
{
NSArray *part = [[NSArray alloc]initWithArray:[[locationarry objectAtIndex:i] componentsSeparatedByString:@","]];
dic=[citywiselatlong objectForKey:[part objectAtIndex:0]];;
[second setCoordinate:CLLocationCoordinate2DMake([[dic valueForKey:@"lat"] floatValue], [[dic valueForKey:@"lng"] floatValue])];
}
if (i==0)
{
[__mapView addAnnotation:first];
[__mapView addAnnotation:second];
}
else
{
[__mapView addAnnotation:second];
}
}
NSLog(@"drawing path completed");
});
});
}
-(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 < routes.count; idx++)
{
CLLocation* currentLocation = [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.0;
region.center.longitude = (maxLon + minLon) / 2.0;
region.span.latitudeDelta = 0.01;
region.span.longitudeDelta = 0.01;
region.span.latitudeDelta = ((maxLat - minLat)<0.0)?100.0:(maxLat - minLat);
region.span.longitudeDelta = ((maxLon - minLon)<0.0)?100.0:(maxLon - minLon);
[__mapView setRegion:region animated:YES];
}
#pragma mark- UITextField delegate method
-(void)locationfind
{
for (int i = 0; i < [locationarry count]; i++) {
NSDictionary *locationDic=[self getLatLongOfPlace:[[locationarry objectAtIndex:i] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
NSDictionary *latLongDic=[[[[locationDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"geometry"]valueForKey:@"location"];
NSArray *part = [[NSArray alloc]initWithArray:[[locationarry objectAtIndex:i] componentsSeparatedByString:@","]];
[citywiselatlong setObject:latLongDic forKey:[part objectAtIndex:0]];
NSLog(@"%@",citywiselatlong);
}
}
#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=%@&sensor=true",place];
NSLog(@"Fired URL:- %@",apiUrlStr);
NSURL* apiUrl = [NSURL URLWithString:[apiUrlStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
NSError* error = nil;
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&error];
NSDictionary *dic=[apiResponse objectFromJSONString];
return dic;
}
@end