2015-03-24 3 views
0

Есть ли какие-либо дополнительные модули для титанового сплава, которые позволяют показывать маршруты на карте Google в приложении iOS? То есть Я хочу показать обозначенный маршрут, показывающий, как автомобиль, например, мог получить от A до B. Я знаю, как добавлять линии к карте, но не знаю, как выработать маршрут или лучше все это сделать автоматически.Как показать направления на карте iOS Google в приложении для титанового сплава

Я, очевидно, могу сделать это, создав веб-просмотр, но скорее не буду делать этого таким образом, если это возможно.

ответ

1

iOS Map Kit может отображать аннотации, тогда может содержать такие места, как направления.

сплава Контроллер: index.js

var MapModule = require('ti.map'); 
var opera = MapModule.createAnnotation({ 
    latitude: -33.8569, 
    longitude: 151.2153, 
    centerOffset: {x: 80, y: 25}, 
    image: 'SydneyOperaHouse.jpg', 
    title: 'Sydney Opera House', 
    subtitle: 'Sydney, New South Wales, Australia', 
// For eventing, use the Map View's click event 
// and monitor the clicksource property for 'rightButton'.  
    rightButton: Ti.UI.iPhone.SystemButton.CONTACT_ADD 
}); 

var bridge = MapModule.createAnnotation({ 
    latitude: -33.852222, 
    longitude: 151.210556, 
    pincolor: MapModule.ANNOTATION_PURPLE, 
    title: 'Sydney Harbour Bridge', 
    subtitle: 'Port Jackson', 
// For eventing, use the Map View's click event 
// and monitor the clicksource property for 'leftButton'. 
    leftButton: Ti.UI.iPhone.SystemButton.INFO_DARK 
}); 

var mapview = MapModule.createView({ 
    mapType: MapModule.NORMAL_TYPE, 
    region: {latitude: -33.87365, longitude: 151.20689, latitudeDelta: 0.1,  longitudeDelta: 0.1 }, 
    annotations: [bridge,opera] 
}); 
$.index.add(mapview); 
$.index.open(); 

enter image description here

Не fortget включить этот модуль в вашем Tiapp.xml т.е.

<modules> 
    <!-- Add this line to your modules section --> 
    <module platform="iphone">ti.map</module> 
</modules> 
+0

Спасибо Эдуардо. Я обновил свой вопрос, чтобы уточнить, что мне нужно построить маршрут по дорогам от А до Б. –

+0

Добавить [маршрут] (http://docs.appcelerator.com/platform/latest/#!/api/Modules .Map.Route-property-points), устанавливая точки вверх. Это должно построить дорогу –

+0

При необходимости тип файла CSV может хранить точки, чтобы включить MapView с маршрутизацией. Демо: https://github.com/appcelerator/titanium_mobile/blob/master/demos/KitchenSink/Resources/examples/map_view2.js#L28 –

0

Вы можете использовать следующий метод для рисования на карте Google // draw path на карте

- (пустоты) getDrivingDirection

{

[mapGoogleView ясно];

cameraGoogleMap = [GMSCameraPosition cameraWithLatitude:[locationSourceLat floatValue] longitude:[locationSourceLong floatValue] zoom:15]; 
[mapGoogleView setCamera:cameraGoogleMap]; 

CLLocationCoordinate2D positionSource = CLLocationCoordinate2DMake([locationDestLat floatValue], [locationDestLong floatValue]); 
GMSMarker *markerSource = [GMSMarker markerWithPosition:positionSource]; 
markerSource.map = mapGoogleView; 

NSString *strDirection = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/directions/json?origin=%@,%@&destination=%@,%@&sensor=false&key=AIzaSyCdq4_-Isxdkvn1LBx8aw7AvdQiWLEqqQ8",locationSourceLat,locationSourceLong,locationDestLat,locationDestLong]; 
NSLog(@"GOOGLE DRAW URL %@",strDirection); 
NSURL *url = [[NSURL alloc]initWithString:[strDirection stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 
NSError* error; 
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
NSArray* latestRoutes = [json objectForKey:@"routes"]; 
NSString *points=[[[latestRoutes objectAtIndex:0] objectForKey:@"overview_polyline"] objectForKey:@"points"]; 

@try 
{ 
    NSArray *temp= [self decodePolyLine:[points mutableCopy]]; 
    GMSMutablePath *path = [GMSMutablePath path]; 

    for(int idx = 0; idx < [temp count]; idx++) 
    { 
     CLLocation *location=[temp objectAtIndex:idx]; 
     [path addCoordinate:location.coordinate]; 
    } 
    // create the polyline based on the array of points. 

    GMSPolyline *rectangle = [GMSPolyline polylineWithPath:path]; 
    rectangle.strokeWidth = 5.0; 
    rectangle.map = mapGoogleView; 
} 
@catch (NSException * e) 
{ 
    // TODO show error 
    NSLog(@""); 
} 
NSLog(@"%f",mapGoogleView.myLocation.coordinate.latitude); 

}

// расшифровывать полилинии рисовать путь

- (NSMutableArray *) decodePolyLine: (NSMutableString *) закодирован { [закодированное replaceOccurrencesOfString: @ "\\" withString: @ Параметры «\»: диапазон NSLiteralSearch: NSMakeRange (0, [закодированная длина])]; NSInteger len = [закодированная длина]; Индекс NSInteger = 0; NSMutableArray * array = [[NSMutableArray alloc] init]; NSInteger lat = 0; NSInteger lng = 0; while (индекс < len) { NSInteger b; NSInteger shift = 0; Результат NSInteger = 0; do { b = [закодированный символAtIndex: index ++] - 63; результат | = (b & 0x1f) < < shift; shift + = 5; } while (b> = 0x20); NSInteger dlat = ((результат & 1)? ~ (Результат >> 1): (результат >> 1)); lat + = dlat; shift = 0; результат = 0; do { b = [закодированный символAtIndex: index ++] - 63; результат | = (b & 0x1f) < < shift; shift + = 5; } while (b> = 0x20); NSInteger dlng = ((результат & 1)?~ (результат >> 1): (результат >> 1)); lng + = dlng; NSNumber * latitude = [[NSNumber alloc] initWithFloat: lat * 1e-5]; NSNumber * longitude = [[NSNumber alloc] initWithFloat: lng * 1e-5]; // printf ("[% f,", [широта doubleValue]); // printf ("% f]", [longitude doubleValue]); CLLocation * loc = [[CLLocation alloc] initWithLatitude: [широта floatValue] долгота: [longitude floatValue]]; [массив addObject: loc]; }

return array; 

}