Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
in this file code for draw route in map.
//
// infoViewController.m
// Googlemapintegration
//
// Created by Benzatine Infotech on 15/03/16.
// Copyright © 2016 Benzatine Infotech. All rights reserved.
//
#import "infoViewController.h"
#import "HCSStarRatingView/HCSStarRatingView.h"
#import "SDWebImage/UIImageView+WebCache.h"
#import "AppDelegate.h"
#import "currentlocationViewController.h"
#import <GoogleMaps/GoogleMaps.h>
#define plceidkey @"AIzaSyCg2Ir-B_SF35DqHONzCHnXwvlqqxPueak"
@interface infoViewController ()
{
NSArray *imgarray;
NSArray *all;
NSArray* routes;
BOOL isUpdatingRoutes;
NSDictionary *q,*q3;
NSArray *distp;
NSArray *steps;
BOOL w;
NSArray *s3;
GMSMapView *mapView ;
}
@property (nonatomic, retain) MKPolyline *routeLine; //your line
@property (nonatomic, retain) MKPolylineView *routeLineView; //overlay view
@end
@interface NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:
(NSString*)urlAddress;
-(NSData*)toJSON;
@end
@implementation NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:
(NSString*)urlAddress
{
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: urlAddress] ];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
-(NSData*)toJSON
{
NSError* error = nil;
id result = [NSJSONSerialization dataWithJSONObject:self
options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
@end
@implementation infoViewController
- (void)viewDidLoad {
[super viewDidLoad];
w=0;
imgarray=[[NSArray alloc]init];
// Do any additional setup after loading the view.
if ([self.contactno isEqualToString:@"Contact Info isn't Available"]) {
self.makecall.hidden=YES;
}
self.addressimage.image=[UIImage imageNamed:@"third_address-128.png"];
self.contactimage.image=[UIImage imageNamed:@"third_contact-128.png"];
self.websiteimage.image=[UIImage imageNamed:@"third_url-128.png"];
self.distanceimage.image=[UIImage imageNamed:@"third_distance-128.png"];
self.getdirectionimage.image=[UIImage imageNamed:@"get.png"];
self.popupview.hidden=YES;
self.maplineview.hidden=YES;
self.userreviews.text=[NSString stringWithFormat:@"%@ Reviews",self.review];
self.rating.enabled=NO;
self.rating.allowsHalfStars=YES;
self.rating.value=self.rate;
self.website.text=self.web;
self.addressofplace.text=self.address;
self.contact.text=self.contactno;
self.nameofplace.text=self.name;
self.distancetolocation.text=[ NSString stringWithFormat:@"%@ Kms",self.disttolocation ];
all=[[NSArray alloc]init];
all=self.alldetail;
self.MAPTAB.hidden=YES;
self.maptabmapview.delegate=self;
self.maptabmapview.showsUserLocation = YES;
[self.maptabmapview setCenterCoordinate:self.maptabmapview.userLocation.location.coordinate animated:YES];
NSString *k=[NSString stringWithFormat:@"AIzaSyBdv3etDLJeJWle7HZcYM4QiBQTmvvAFUY"];
NSString *URLString1 = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/directions/json?origin=%0.8f,%0.8f&destination=%0.8f,%0.8f&key=%@", theAppDelegate.lang,theAppDelegate.long1,self.destlatitude,self.destlongitude,k];
NSURLRequest *request1 = [NSURLRequest requestWithURL:[NSURL
URLWithString:URLString1]];
NSData *response = [NSURLConnection sendSynchronousRequest:request1
returningResponse:nil error:nil];
NSError *error;
q=[NSJSONSerialization
JSONObjectWithData:response //1
options:kNilOptions
error:&error];
distp=[[NSArray alloc]init];
distp=[[[[[[[q valueForKey:@"routes"]valueForKey:@"legs"] valueForKey:@"steps"]valueForKey:@"distance" ]objectAtIndex:0]objectAtIndex:0]valueForKey:@"text"] ;
steps=[[NSArray alloc]init];
CLLocation *str=[[CLLocation alloc]initWithLatitude:theAppDelegate.lang longitude:theAppDelegate.long1];
CLLocation *end=[[CLLocation alloc]initWithLatitude:self.destlatitude longitude:self.destlongitude];
[self callGoogleServiceToGetRouteDataFromSource:str toDestination:end];
NSString *URLString13 = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/details/json?placeid=%@&key=%@", self.images,plceidkey];
NSURLRequest *request12 = [NSURLRequest requestWithURL:[NSURL
URLWithString:URLString13]];
NSData *response2 = [NSURLConnection sendSynchronousRequest:request12
returningResponse:nil error:nil];
NSError *error3;
q3=[NSJSONSerialization
JSONObjectWithData:response2 //1
options:kNilOptions
error:&error3];
s3=[[NSArray alloc]init];
s3=[[[q3 valueForKey:@"result"] valueForKey:@"photos"] valueForKey:@"photo_reference"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
[[NSURLCache sharedURLCache] removeAllCachedResponses];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
if (s3==nil) {
return 1;
}
else
{
return s3.count;
}
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
UIImageView *thumbail = (UIImageView*) [cell viewWithTag:800];
// UILabel *name = (UILabel*)[cell viewWithTag:20];
thumbail.layer.cornerRadius = 15.0f;
thumbail.layer.masksToBounds = YES;
if (s3==nil) {
thumbail.image=[UIImage imageNamed:@"default_list_image.png"];
}else
{
NSString *URLString1 = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/photo?maxwidth=150&photoreference=%@&key=%@",[s3 objectAtIndex:indexPath.row] ,plceidkey];
[thumbail sd_setImageWithURL:[NSURL URLWithString:URLString1]
placeholderImage:[UIImage imageNamed:@"default.png"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
thumbail.image = image;
}];
}
return cell;
}
- (void)removeAnimate
{
[UIView animateWithDuration:.25 animations:^{
self.popupview.transform = CGAffineTransformMakeScale(1.3, 1.3);
self.popupview.alpha = 0.0;
} completion:^(BOOL finished) {
if (finished) {
[self.popupview setHidden:YES];
}
}];
}
-(void)addPopUpZoomAnimatioToPickerView :(UIView*)view
{
view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.001, 0.001);
[UIView animateWithDuration:0.3/1.5 animations:^{
view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.1, 1.1);
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.3/2 animations:^{
view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.9, 0.9);
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.3/2 animations:^{
view.transform = CGAffineTransformIdentity;
}];
}];
}];
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
[self.popupview setHidden:NO];
self.popupview.alpha = 1.0;
NSString *URLString14 = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/photo?maxwidth=1000&photoreference=%@&key=%@",[s3 objectAtIndex:indexPath.row] ,plceidkey];
// [self showInView:self.view animated:YES];
[self addPopUpZoomAnimatioToPickerView:self.popupview];
[self.image sd_setImageWithURL:[NSURL URLWithString:URLString14]
placeholderImage:[UIImage imageNamed:@"default.png"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
self.image.image = image;
}];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.reviewtable) {
if ([all isEqual: @"No Review"]) {
return 0;
}
else
{
return all.count;
}
}else
{
return distp.count;
}
}
-(void)callGoogleServiceToGetRouteDataFromSource:(CLLocation *)sourceLocation toDestination:(CLLocation *)destinationLocation{
NSString *k=[NSString stringWithFormat:@"AIzaSyBdv3etDLJeJWle7HZcYM4QiBQTmvvAFUY"];
NSString *baseUrl = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/directions/json?origin=%0.8f,%0.8f&destination=%0.8f,%0.8f&sensor=false&key=%@", sourceLocation.coordinate.latitude, sourceLocation.coordinate.longitude, destinationLocation.coordinate.latitude, destinationLocation.coordinate.longitude,k];
NSURL *url = [NSURL URLWithString:[baseUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
GMSMutablePath *path = [GMSMutablePath path];
NSError *error = nil;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
routes = [result objectForKey:@"routes"];
NSDictionary *firstRoute = [routes objectAtIndex:0];
NSDictionary *leg = [[firstRoute objectForKey:@"legs"] objectAtIndex:0];
NSDictionary *steps1 = [leg objectForKey:@"steps"];
//proper zoom for center location of beetween two point start
double centerLat = [[[[steps1 valueForKey:@"start_location"] valueForKey:@"lat"] objectAtIndex:((unsigned long)[steps count]/2)] doubleValue];
double centerLng = [[[[steps1 valueForKey:@"start_location"] valueForKey:@"lng"] objectAtIndex:((unsigned long)[steps count]/2)] doubleValue];
double dist = [[[leg valueForKey:@"distance"] valueForKey:@"value"] doubleValue];
double centerZoom;
if(dist > 1000){
double midd = (log(dist/1000))/0.8000;
centerZoom = 15-midd;
}else{
centerZoom = 15;
}
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:centerLat
longitude:centerLng
zoom:centerZoom];
mapView = [GMSMapView mapWithFrame:self.maptabmapview.bounds camera:camera];
if ([theAppDelegate.maptypevalue isEqualToString:@"0"] ) {
[mapView setMapType:kGMSTypeSatellite];
}else if ([theAppDelegate.maptypevalue isEqualToString:@"1"])
{
[mapView setMapType:kGMSTypeNormal];
}else
{
[mapView setMapType:kGMSTypeHybrid];
}
int stepIndex = 0;
CLLocationCoordinate2D stepCoordinates[1 + [steps1 count] + 1];
for (NSDictionary *step in steps1) {
NSDictionary *start_location = [step objectForKey:@"start_location"];
stepCoordinates[++stepIndex] = [self coordinateWithLocation:start_location];
[path addCoordinate:[self coordinateWithLocation:start_location]];
NSString *polyLinePoints = [[step objectForKey:@"polyline"] objectForKey:@"points"];
GMSPath *polyLinePath = [GMSPath pathFromEncodedPath:polyLinePoints];
for (int p=0; p<polyLinePath.count; p++) {
[path addCoordinate:[polyLinePath coordinateAtIndex:p]];
}
if ([steps count] == stepIndex){
NSDictionary *end_location = [step objectForKey:@"end_location"];
stepCoordinates[++stepIndex] = [self coordinateWithLocation:end_location];
[path addCoordinate:[self coordinateWithLocation:end_location]];
}
}
GMSPolyline *polyline = nil;
polyline = [GMSPolyline polylineWithPath:path];
polyline.strokeColor = [UIColor blueColor];
polyline.strokeWidth = 3.f;
polyline.map = mapView;
// Creates a marker in the center of the map.
CLLocationCoordinate2D startLoc = CLLocationCoordinate2DMake( theAppDelegate.lang, theAppDelegate.long1);
CLLocationCoordinate2D endLoc = CLLocationCoordinate2DMake( self.destlatitude,self.destlongitude);
[self setMarker:mapView imageName:@"startPoint.png" location:startLoc titleString:@"Current Location"];
[self setMarker:mapView imageName:@"9.png" location:endLoc titleString:@"Destination Location"];
[self.maptabmapview addSubview:mapView];
}];
}
- (CLLocationCoordinate2D)coordinateWithLocation:(NSDictionary*)location
{
double latitude = [[location objectForKey:@"lat"] doubleValue];
double longitude = [[location objectForKey:@"lng"] doubleValue];
return CLLocationCoordinate2DMake(latitude, longitude);
}
-(void)setMarker:(GMSMapView *)viewMap imageName:(NSString *)image location:(CLLocationCoordinate2D)markLocation titleString:(NSString *)title{
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = markLocation;
marker.title = title;
marker.icon = [UIImage imageNamed:image];
marker.map = viewMap;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{ static NSString *CellIdentifier;
UITableViewCell *cell;
if (tableView == self.reviewtable) {
CellIdentifier = @"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
UILabel *username = (UILabel*) [cell viewWithTag:1];
UILabel *usertext = (UILabel*) [cell viewWithTag:4];
UILabel *date = (UILabel*) [cell viewWithTag:3];
HCSStarRatingView *rating=(HCSStarRatingView *)[cell viewWithTag:2];
rating.allowsHalfStars = YES;
rating.enabled=NO;
username.text=[[all valueForKey:@"author_name"]objectAtIndex:indexPath.row];
rating.value=[[[all valueForKey:@"rating"]objectAtIndex:indexPath.row] floatValue];
usertext.text=[[all valueForKey:@"text"]objectAtIndex:indexPath.row];
NSString *epochTime =[[all valueForKey:@"time"]objectAtIndex:indexPath.row];
// (Step 1) Convert epoch time to SECONDS since 1970
NSTimeInterval seconds = [epochTime doubleValue];
// (Step 2) Create NSDate object
NSDate *epochNSDate = [[NSDate alloc] initWithTimeIntervalSince1970:seconds];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/MM/yyyy"];
NSString *stringFromDate = [formatter stringFromDate:epochNSDate];
date.text=stringFromDate;
}else
{
CellIdentifier = @"directioncell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
steps=[[[[[[q valueForKey:@"routes"]valueForKey:@"legs"] valueForKey:@"steps"]valueForKey:@"html_instructions" ]objectAtIndex:0]objectAtIndex:0];
UILabel *l=(UILabel*)[cell viewWithTag:65];
UILabel *l1=(UILabel*)[cell viewWithTag:66];
UIImageView *directionimage=(UIImageView *)[cell viewWithTag:658];
directionimage.image=[UIImage imageNamed:@"arrow.png"];
l.text=[distp objectAtIndex:indexPath.row];
NSError *err;
NSAttributedString* str1 = [[NSAttributedString alloc]
initWithData:[[steps objectAtIndex:indexPath.row] dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}
documentAttributes:nil
error:&err];
l1.text=[NSString stringWithFormat:@"%@",[str1 string]];
}
return cell;
}
-(void)viewDidAppear:(BOOL)animated
{
self.constraint.constant=self.reviewtable.contentSize.height;
self.mainviewconstaint.constant=self.mainviewconstaint.constant+self.constraint.constant-180;
self.reviewtable.userInteractionEnabled=NO;
}
- (IBAction)infobuttontap:(id)sender {
self.infolineview.hidden=NO;
self.maplineview.hidden=YES;
self.MAPTAB.hidden=YES;
self.infotabview.hidden=NO;
}
- (IBAction)mapbuttontap:(id)sender {
self.infolineview.hidden=YES;
self.maplineview.hidden=NO;
self.MAPTAB.hidden=NO;
self.infotabview.hidden=YES;
self.directionviewdistance.text =[[[[[[q valueForKey:@"routes"]valueForKey:@"legs"]valueForKey:@"distance"]objectAtIndex:0]objectAtIndex:0]valueForKey:@"text"];
self.directionviewtime.text=[[[[[[q valueForKey:@"routes"]valueForKey:@"legs"]valueForKey:@"duration"]objectAtIndex:0]objectAtIndex:0]valueForKey:@"text"];
}
- (IBAction)backtap:(id)sender
{
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)linkbutton:(id)sender {
NSURL *url = [NSURL URLWithString:self.website.text];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
}
-(void)viewSlideInFromBottomToTop:(UIView *)views
{
CATransition *transition = nil;
transition = [CATransition animation];
transition.duration = 0.5;//kAnimationDuration
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionPush;
transition.subtype =kCATransitionFromTop ;
transition.delegate = self;
[views.layer addAnimation:transition forKey:nil];
}
-(void)viewSlideInFromtoptobottom:(UIView *)views
{
CATransition *transition = nil;
transition = [CATransition animation];
transition.duration = 0.5;//kAnimationDuration
transition.type = kCATransitionPush;
transition.subtype =kCATransitionFromBottom ;
transition.delegate = self;
[views.layer addAnimation:transition forKey:nil];
}
- (IBAction)openclose:(id)sender {
if (w) {
[UIView animateWithDuration:0.5
delay:0.0
options: UIViewAnimationOptionCurveEaseOut
animations:^{
self.addressconstraint.constant=52;
[self.adressview layoutIfNeeded];
}
completion:^(BOOL finished){
self.openclosebtn.transform = CGAffineTransformMakeRotation(0.0*M_PI/180.0);
}];
w=0;
}else{
[UIView animateWithDuration:0.5
delay:0.0
options: UIViewAnimationOptionCurveEaseOut
animations:^{
self.addressconstraint.constant=self.addressconstraint.constant+self. MAPTAB.frame.size.height-53;
[self.adressview layoutIfNeeded];
}
completion:^(BOOL finished){
self.openclosebtn.transform = CGAffineTransformMakeRotation(180.0*M_PI/180.0);
}];
w=1;
}
}
- (IBAction)dismispopup:(id)sender {
[self removeAnimate];
}
- (IBAction)makephonecall:(id)sender {
if ([self.contactno isEqualToString:@"Contact Info isn't Available"]) {
self.makecall.hidden=YES;
}else
{
self.makecall.hidden=NO;
NSString *whitespaceString = [NSString stringWithFormat:@"%@",self.contactno];
NSString *trimmedString = [whitespaceString stringByReplacingOccurrencesOfString:@" " withString:@""];
NSString *phone=[@"tel:" stringByAppendingString:trimmedString];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phone]];
}
}
- (IBAction)getdirectionbutton:(id)sender {
self.infolineview.hidden=YES;
self.maplineview.hidden=NO;
self.MAPTAB.hidden=NO;
self.infotabview.hidden=YES;
self.directionviewdistance.text =[[[[[[q valueForKey:@"routes"]valueForKey:@"legs"]valueForKey:@"distance"]objectAtIndex:0]objectAtIndex:0]valueForKey:@"text"];
self.directionviewtime.text=[[[[[[q valueForKey:@"routes"]valueForKey:@"legs"]valueForKey:@"duration"]objectAtIndex:0]objectAtIndex:0]valueForKey:@"text"];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.