SHLineGraphView - Set graph origin value - ios

Using SHLineGraphView
I want to specify the origin of my graph to a different value other than 0.
The issue was already created here Min/Max draw Y axis but the owner seems uninterested in solving it.
This is what I have now
SHLineGraphView.m
#define BOTTOM_MARGIN_TO_LEAVE 30.0
#define TOP_MARGIN_TO_LEAVE 30.0
#define INTERVAL_COUNT 10
//INTERVAL_COUNT - 3 -> Limits the y-axis to 60 but
//not the entire graph.
- (void)drawYLabels:(SHPlot *)plot {
double yRange = [_yAxisRange doubleValue]; // this value will be in dollars
double yIntervalValue = yRange / INTERVAL_COUNT;
double intervalInPx = (self.bounds.size.height - BOTTOM_MARGIN_TO_LEAVE ) / (INTERVAL_COUNT - 3);
NSLog(#"interval px %f",intervalInPx);
NSMutableArray *labelArray = [NSMutableArray array];
float maxWidth = 0;
for(int i= 0; i <= INTERVAL_COUNT - 3 ; i++){
CGPoint currentLinePoint = CGPointMake(_leftMarginToLeave, i * intervalInPx);
CGRect lableFrame = CGRectMake(0, currentLinePoint.y - (intervalInPx / 2), 100, intervalInPx);
NSLog(#"label frame %f", lableFrame.origin.y);
//if(i != 0) {
UILabel *yAxisLabel = [[UILabel alloc] initWithFrame:lableFrame];
yAxisLabel.backgroundColor = [UIColor clearColor];
yAxisLabel.font = (UIFont *)_themeAttributes[kYAxisLabelFontKey];
yAxisLabel.textColor = (UIColor *)_themeAttributes[kYAxisLabelColorKey];
yAxisLabel.textAlignment = NSTextAlignmentCenter;
float val = (yIntervalValue * (10 - i));
NSLog(#"value %f", val);
if(val > 0){
yAxisLabel.text = [NSString stringWithFormat:#"%.1i%#", (int)val, _yAxisSuffix];
} else {
yAxisLabel.text = [NSString stringWithFormat:#"%.0f", val];
}
[yAxisLabel sizeToFit];
CGRect newLabelFrame = CGRectMake(0, currentLinePoint.y - (yAxisLabel.layer.frame.size.height / 2), yAxisLabel.frame.size.width, yAxisLabel.layer.frame.size.height);
yAxisLabel.frame = newLabelFrame;
if(newLabelFrame.size.width > maxWidth) {
maxWidth = newLabelFrame.size.width;
}
[labelArray addObject:yAxisLabel];
[self addSubview:yAxisLabel];
//}
}
viewController.m
_graphView.yAxisRange = #(200);
The y-axis is ok but the graph is still plotted from origin 0.

Create a yAxisMinValue property
#property (nonatomic, strong) NSNumber *yAxisMinValue;
...and update your drawYLabels function as follows:
- (void)drawYLabels:(SHPlot *)plot {
double yRange = [_yAxisRange doubleValue]; // this value will be in dollars
double yRangeMin = [_yAxisMinValue doubleValue];
NSLog(#"yRange: %f", yRange);
NSLog(#"yRangeMin: %f", yRangeMin);
double yIntervalValue = (yRange - yRangeMin) / INTERVAL_COUNT;
NSLog(#"yIntervalValue: %f", yIntervalValue);
double intervalInPx = (self.bounds.size.height - BOTTOM_MARGIN_TO_LEAVE ) / (INTERVAL_COUNT +1);
NSMutableArray *labelArray = [NSMutableArray array];
float maxWidth = 0;
for(int i= INTERVAL_COUNT + 1; i >= 0; i--){
NSLog(#"i = %d",i);
CGPoint currentLinePoint = CGPointMake(_leftMarginToLeave, i * intervalInPx);
CGRect lableFrame = CGRectMake(0, currentLinePoint.y - (intervalInPx / 2), 100, intervalInPx);
if(i != 0) {
UILabel *yAxisLabel = [[UILabel alloc] initWithFrame:lableFrame];
yAxisLabel.backgroundColor = [UIColor clearColor];
yAxisLabel.font = (UIFont *)_themeAttributes[kYAxisLabelFontKey];
yAxisLabel.textColor = (UIColor *)_themeAttributes[kYAxisLabelColorKey];
yAxisLabel.textAlignment = NSTextAlignmentCenter;
float val = (yIntervalValue * (10 - i)) + yRangeMin;
if(val > yRangeMin){
yAxisLabel.text = [NSString stringWithFormat:#"%.1f%#", val, _yAxisSuffix];
NSLog(#"%.1f%#", val, _yAxisSuffix);
} else {
yAxisLabel.text = [NSString stringWithFormat:#"%.1f", val];
NSLog(#"%.1f", val);
}
[yAxisLabel sizeToFit];
CGRect newLabelFrame = CGRectMake(0, currentLinePoint.y - (yAxisLabel.layer.frame.size.height / 2), yAxisLabel.frame.size.width, yAxisLabel.layer.frame.size.height);
yAxisLabel.frame = newLabelFrame;
if(newLabelFrame.size.width > maxWidth) {
maxWidth = newLabelFrame.size.width;
}
[labelArray addObject:yAxisLabel];
[self addSubview:yAxisLabel];
}
}

Related

Move Buttons to image targets

I am new in objective c and now i try to build game like What's the word and i have some problems with targets coordinates and button passing into targets. I create a -(void)dealRandomWord here I am take randome a word from plist and output all my subview on screen. I call it from viewDidLoad: [self dealRandomWord].
And here is my problem:
#pragma mark Targets
_targets = [NSMutableArray arrayWithCapacity:word1len];
for (NSInteger i = 0; i < word1len; i++) {
NSString *letter = [word1 substringWithRange:NSMakeRange(i, 1)];
TargetView *target = [[TargetView alloc] initWithLetter:letter andSideLength: letterSide];
target.center = CGPointMake(xCenterTarget + i * (letterSide + kLetterMargin), placesView.frame.size.height / 2);
[placesView addSubview:target];
NSLog(#"biiitch %#", NSStringFromCGPoint(target.center));
}
In target.center i have the coordinates of targets where i want to move my buttons by click. When i click one of the button it moved but not in the target, it happens because in
-(void)placeForButton:(InputButtonsView*)inputButtonsView atTarget:(TargetView*)targetView {
targetView.center coordinate equal {0,0}
How can i pass coordinates for each of target to my button that it's move to target. Every next button should move to next target.
Here is image: Screenshot
Thanks for any help!!!
Here is my code:
-(void)dealRandomWord {
#pragma mark Level and words init
NSAssert(self.level.words, #"Level not loaded");
// random word from plist
NSInteger randomIndex = arc4random()%[self.level.words count];
NSArray* anaPair = self.level.words[ randomIndex ];
NSString* question = anaPair[0]; // question
NSString* word1 = anaPair[1]; // answer
NSString* word2 = anaPair[2]; // some letters
NSString* helpstr = anaPair[3]; // helper
NSLog(#"qweqweq %# %# %#" , word1 , word2 , helpstr);
NSInteger word1len = [word1 length];
NSInteger word2len = [word2 length];
NSLog(#"phrase1[%li]: %#", (long)word1len, word1);
NSLog(#"phrase2[%li]: %#", (long)word2len, word2);
NSLog(#"question %#", question);
float letterSide = ceilf (kScreenWidth * 0.9 / (float)MAX(word1len, word2len) - kLetterMargin);
float xOffset = (kScreenWidth - (float)MAX(word1len, word2len) * (letterSide + kLetterMargin))/3;
xOffset += letterSide/2;
float yOffset = 1.5* letterSide;
#pragma mark QuestionView init
QuestionView *quv = [[QuestionView alloc] init];
quv.questionLabel.text = question;
[self.view addSubview:quv];
quv.center = CGPointMake(185, 210);
#pragma mark PlacesView init
PlacesView *placesView = [[PlacesView alloc] init];
[self.view addSubview:placesView];
placesView.center = CGPointMake(185, 400);
//Center x position for targets
float xCenterTarget = ((placesView.frame.size.width / 2) - ((word1len / 2) * letterSide ));
#pragma mark LetterView init
LettersView *lettersView = [[LettersView alloc] init];
[self.view addSubview:lettersView];
lettersView.center = CGPointMake(185, 500);
#pragma mark Targets
_targets = [NSMutableArray arrayWithCapacity:word1len];
for (NSInteger i = 0; i < word1len; i++) {
NSString *letter = [word1 substringWithRange:NSMakeRange(i, 1)];
TargetView *target = [[TargetView alloc] initWithLetter:letter andSideLength: letterSide];
target.center = CGPointMake(xCenterTarget + i * (letterSide + kLetterMargin), placesView.frame.size.height / 2);
[placesView addSubview:target];
NSLog(#"coord target init %#", NSStringFromCGPoint(target.center));
}
#pragma mark LettersView init
//init letters list
_letters = [NSMutableArray arrayWithCapacity: word2len];
//create letter
for (NSInteger i=0;i<word2len;i++) {
NSString* letter = [word2 substringWithRange:NSMakeRange(i, 1)];
if (![letter isEqualToString:#" "]) {
InputButtonsView *buttons = [[InputButtonsView alloc] initWithLetter:letter andSideLength:letterSide];
buttons.center = CGPointMake(xOffset + i * (letterSide + kLetterMargin), lettersView.frame.size.height /2); // "/3*4" kScreenHeight/4*3
if (i > 6) {
buttons.center = CGPointMake(- 7 * xOffset + i * (letterSide + kLetterMargin), lettersView.frame.size.height/2 + (letterSide + kLetterMargin)); // "/3*4"
}
buttons.clickDelegate = self;
[lettersView addSubview:buttons];
//[buttons addSubview:buttons];
[_letters addObject: letter];
}
}
}
-(void)inputButtonView:(InputButtonsView *)inputButtonView didPress:(CGPoint)didPress {
TargetView *targetView = nil;
NSLog(#"did press x = %f, y = %f", didPress.x , didPress.y);
for(TargetView *tv in _targets) {
if(CGRectContainsPoint(tv.frame, didPress)){
targetView = tv;
break;
}
}
[self placeForButton:inputButtonView atTarget:targetView];
if (targetView != nil) {
NSLog(#"Kek");
if ([targetView.letter isEqualToString: inputButtonView.letter]) {
[self placeForButton:inputButtonView atTarget:targetView];
}
}
}
-(void)placeForButton:(InputButtonsView*)inputButtonsView atTarget:(TargetView*)targetView {
targetView.isMatched = YES;
inputButtonsView.isMatched = YES;
inputButtonsView.userInteractionEnabled = NO;
CGPoint originButtons = [self.view.superview convertPoint:CGPointZero fromView:inputButtonsView];
CGPoint originTargets = [self.view.superview convertPoint:CGPointZero fromView:targetView];
inputButtonsView.center = originButtons;
targetView.center = originTargets;
NSLog(#"OriginButtons = %# , OriginTargets = %#", NSStringFromCGPoint(originButtons) , NSStringFromCGPoint(originTargets));
inputButtonsView.center = targetView.center;
NSLog(#"TARGETVIEW.center %#", NSStringFromCGPoint(targetView.center));
}

How to generate random letters as per the word

I’m developing word puzzle game,where one word is given.according to that word the random letters are generated…for that, i applied below logic but some how the random letters not generated as per the given word.
NSMutableArray *ArrOfABCD = [[NSMutableArray alloc]
initWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z",
nil];
float x = 70;
float y = 100;
float width = 30;
float height = 20;
for(int i =0;i<32;i++)
{
NSUInteger randomIndex = arc4random() %(ArrOfABCD.count);
UIButton *btnLetter = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btnLetter setFrame:CGRectMake(x, y, width, height)];
[btnLetter setTitle:[NSString stringWithFormat:#"%#",ArrOfABCD[randomIndex]]
forState:UIControlStateNormal];
[self.view addSubview:btnLetter];
x = x + width + 30;
if((i+1)%4==0)
{
x = 70;
y = y + height + 20;
}
}
can any one suggest me that where i made mistake?
You should generate the unique random number
NSMutableArray* ArrOfWords = [[NSMutableArray alloc] initWithObjects:#"Good",#"Home",#"Beauty",#"Good",nil];
NSMutableArray *ArrOfABCD = [[NSMutableArray alloc] initWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z", nil];
NSMutableArray *arrDuplicate=[[NSMutableArray alloc]init];
float x = 70;
float y = 100;
float width = 30;
float height = 20;
NSInteger rowIndex=4;
NSString *dataString=[ArrOfWords objectAtIndex:0];
NSMutableArray *arrNumber = [[NSMutableArray alloc]init];
for (int i = 0; i < [dataString length]; i++) {
NSInteger index=arc4random_uniform(rowIndex)+rowIndex;
NSNumber *number=[NSNumber numberWithInt:index];
while ([arrDuplicate containsObject:number] ) {
NSInteger index=arc4random_uniform(rowIndex)+rowIndex;
number=[NSNumber numberWithInt:index];
}
[arrNumber addObject:number];
[arrDuplicate addObject:number];
}
[arrDuplicate removeAllObjects];
NSMutableArray *arrayChar = [NSMutableArray array];
for (int i = 0; i < [dataString length]; i++) {
[arrayChar addObject:[NSString stringWithFormat:#"%C", [dataString characterAtIndex:i]]];
}
for(int i =0;i<32;i++)
{
NSString *str=[ArrOfABCD objectAtIndex:arc4random_uniform(ArrOfABCD.count)];
if ([arrNumber containsObject:[NSNumber numberWithInt:i]] ) {
str=[arrayChar objectAtIndex:arrDuplicate.count];
[arrDuplicate addObject:str];
}
NSLog(#"%#",str);
UIButton *btnLetter = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btnLetter setFrame:CGRectMake(x, y, width, height)];
[btnLetter setTitle:str forState:UIControlStateNormal];
x = x + width + 30;
if((i+1)%4==0)
{
x = 70;
y = y + height + 20;
}
}

Accelerometer calculations resulting in inf

I have been trying to get to move an UIImageView with the accelerometer, however I have run into an issue. When I try to smooth out the data and work out the acceleration of the data from the original position, the values return infinity. I'm not really sure what I'm doing wrong!
Here's my code:
- (void)viewDidLoad {
gameObjects = [NSMutableArray arrayWithObjects: nil];
UIImageView* mainChar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
[mainChar setCenter:CGPointMake(screenHeight/2, screenWidth/2)];
mainChar.image = [UIImage imageNamed:#"dot.png"];
[self.view insertSubview:mainChar atIndex:2];
[gameObjects addObject:mainChar];
mainChar = nil;
AvData = [NSMutableArray arrayWithObjects: nil];
motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 20;
[motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData* accelerationData, NSError* error) {
if (defaultData == nil) {defaultData = accelerationData;}
[self accelerometerUpdate:accelerationData];
}];
}
-(void) accelerometerUpdate:(CMAccelerometerData*)aData {
//Accelerometer Smoothing
[AvData addObject:aData];
if ([AvData count] >= 20) {[AvData removeObjectAtIndex:0];}
float avX = 0;
float avY = 0;
float avZ = 0;
for (int i = 0; i < [AvData count]; i++) {
avX = avX + [[AvData objectAtIndex:i] acceleration].x;
avY = avY + [[AvData objectAtIndex:i] acceleration].y;
avZ = avZ + [[AvData objectAtIndex:i] acceleration].z;
}
avX = avX/([AvData count] - 1);
avY = avY/([AvData count] - 1);
avZ = avZ/([AvData count] - 1);
//Calculate the delta from original device acceleration value
float accX = defaultData.acceleration.x - avX;
float accY = defaultData.acceleration.y - avY;
//float accZ = defaultData.acceleration.z - avZ;
NSLog([NSString stringWithFormat:#"%f", accY]);
UIImageView* mainChar = [gameObjects objectAtIndex:0];
[mainChar setCenter:CGPointMake(mainChar.center.x + accX, mainChar.center.y + accY)];
//accX and accY are infinity for some reason, and so the image disappears!
mainChar = nil;
}
The weird thing is when I NSLog accY, it returns a proper value. What am I doing wrong?
Off the top of my head:
When you get to these lines:
avX = avX/([AvData count] - 1);
avY = avY/([AvData count] - 1);
avZ = avZ/([AvData count] - 1);
If count == 1 at that point, your code will divide by zero. I would expect that to crash, but if not, the result would be infinity or NAN. (I'd expect NAN, but it might return INF if it doesn't throw an exception. I'd need to test it or look it up to be sure.)

Set Time Clicking on Dial

I am working on an alarm app in which I have to show an analogue clock. The functionality is to set time by clicking on the circumference of the circle displayed as the clock dial.
I have succesfully done this too. But the issue comes at 6 O'Clock or 30 min. The angle comes out to be nan for that which makes my smooth clock totally abrupt.
Here is the code.
myPath1 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(5, 5, 244, 244)];
[myPath1 closePath];
[myPath1 setLineWidth:20];
// Draw a shape Layer with Triangle Path
CAShapeLayer *shapeLayer1 = [CAShapeLayer layer];
shapeLayer1.fillColor = [UIColor clearColor].CGColor;
shapeLayer1.strokeColor = [UIColor clearColor].CGColor;
shapeLayer1.lineWidth = 20;
shapeLayer1.path = myPath1.CGPath;
// Add it to your view
[circleView.layer addSublayer:shapeLayer1];
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:circleView];
if([self containsPointOnStroke:currentPoint onPath:myPath1])
{
[self calculateAngle:currentPoint];
}
}
- (BOOL)containsPointOnStroke:(CGPoint)point onPath:(UIBezierPath *)path
{
CGPathRef cgPath = path.CGPath;
CGPathRef strokedPath = CGPathCreateCopyByStrokingPath(cgPath, NULL, 10,
kCGLineCapRound, kCGLineJoinRound, 1);
BOOL pointIsNearPath = CGPathContainsPoint(strokedPath, NULL, point, NO);
CGPathRelease(strokedPath);
return pointIsNearPath;
}
//---- calculate angle from the point of touch taking center as the reference ----//
- (void) calculateAngle : (CGPoint)currentPoint
{
double distance = sqrt(pow((currentPoint.x - 127), 2.0) + pow((currentPoint.y - 5), 2.0));
float val = ((2 * 14884) - powf((distance), 2)) / (2 * 14884);
float angleVal = acosf(val) * 180/M_PI;
float timeval = angleVal;
//NSLog(#"angleVal : %f timeVal : %.2f", angleVal, timeval);
if (isnan(angleVal))
{
// if the value of the angle val is infinite
if(check == 0)
[hourBtn setTitle:#"06" forState:UIControlStateNormal];
else
[minBtn setTitle:#"30" forState:UIControlStateNormal];
}
else
{
if(check == 0)
{
if (currentPoint.x >= 127)
[hourBtn setTitle:[self getHour:timeval reverseTIme:NO] forState:UIControlStateNormal];
else
[hourBtn setTitle:[self getHour:timeval reverseTIme:YES] forState:UIControlStateNormal];
}
else
{
if (currentPoint.x >= 127)
[minBtn setTitle:[self getMin:timeval reverseTIme:NO] forState:UIControlStateNormal];
else
[minBtn setTitle:[self getMin:timeval reverseTIme:YES] forState:UIControlStateNormal];
}
}
[timeLbl setText:[NSString stringWithFormat:#"%02d:%02d",[hourBtn.titleLabel.text intValue], [minBtn.titleLabel.text intValue]]];
}
//---- get the hour time from the angle ----//
- (NSString *) getHour :(float) angle reverseTIme:(BOOL) reverseCheck
{
int minuteCount = angle * 2;
int quo = minuteCount / 60;
int temp = quo;
if(quo == 0)
quo = 12;
NSString *timeStr = [NSString stringWithFormat:#"%02d", quo];
quo = temp;
if (reverseCheck)
{
int revQuo = 11 - quo;
if(revQuo == 0)
revQuo = 12;
timeStr = [NSString stringWithFormat:#"%02d", revQuo];
}
return timeStr;
}
// get the min time from the angle
- (NSString *) getMin :(float) angle reverseTIme:(BOOL) reverseCheck
{
int minuteCount = angle;
int rem = minuteCount / 6;
NSString *timeStr = [NSString stringWithFormat:#"%02d", rem];
if (reverseCheck)
{
int revRem = 60 - rem;
if(revRem == 60)
revRem = 0;
timeStr = [NSString stringWithFormat:#"%02d", revRem];
}
//NSLog(#"timeStr : %#", timeStr);
return timeStr;
}

With what coordinates do i use to manually draw a custom path with an MKMapView?

There are CLLocation2D points, MKMapPoints, MKCoordinates, and convertCoordinate:toPointInView: which all give you points in one form or another. I am drawing a custom route in:
- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context {
Whats the proper point to use for drawing?
routeView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, mapView.frame.size.width, mapView.frame.size.height)];
routeView.userInteractionEnabled = NO;
[mapView addSubview:routeView];
And
-(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);
}
You can use google api like-
Define approirate variable in .h-
NSArray *arrRoutePoints;
MKPolygon *objpolygon;
MKPolyline *objpolyline;
Call function like where you want -
self.arrRoutePoints=[self getRoutePointFrom:newSource to:newDestination];
[self drawRoute];
Function Code :
- (NSArray*)getRoutePointFrom:(MKPointAnnotation *)origin to:(MKPointAnnotation *)destination
{
NSString *saddress=[NSString stringWithFormat:#"%f,%f",origin.coordinate.latitude,origin.coordinate.longitude];
NSString *daddress=[NSString stringWithFormat:#"%f,%f",destination.coordinate.latitude,destination.coordinate.longitude];
NSString *apiUrlString=[NSString stringWithFormat:#"http://maps.google.com/maps?output=dragdir&saddr=%#&daddr=%#", saddress, daddress];
NSURL *apiUrl=[NSURL URLWithString:apiUrlString];
NSError *error;
NSString *apiResponse=[NSString stringWithContentsOfURL:apiUrl encoding:NSUTF8StringEncoding error:&error];
NSRange range;
range=[apiResponse rangeOfString:#"points:\\\"([^\\\"]*)\\\"" options:NSRegularExpressionSearch];
NSString *encodedPoint=[apiResponse substringWithRange:range];
NSLog(#"Encode lentgh %d",[encodedPoint length]);
encodedPoint=[encodedPoint stringByReplacingOccurrencesOfString:#"points:\"" withString:#""];
encodedPoint=[encodedPoint stringByReplacingOccurrencesOfString:#"\"" withString:#""];
return [self decodePolyLine:[encodedPoint mutableCopy]];
}
- (NSMutableArray *)decodePolyLine:(NSMutableString *)encodedString
{
[encodedString replaceOccurrencesOfString:#"\\\\" withString:#"\\"
options:NSLiteralSearch
range:NSMakeRange(0, [encodedString length])];
NSInteger len = [encodedString 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 = [encodedString 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 {
if(index<len)
{
b = [encodedString characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
}
else
{
break;
}
} 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("\n[%f,", [latitude doubleValue]);
printf("%f]", [longitude doubleValue]);
CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
[array addObject:loc];
}
return array;
}
- (void)drawRoute
{
int numPoints=[arrRoutePoints count];
if(numPoints >1)
{
CLLocationCoordinate2D *coord=malloc(numPoints *sizeof(CLLocationCoordinate2D));
for(int i=0;i<numPoints;i++)
{
CLLocation *current=[arrRoutePoints objectAtIndex:i];
NSLog(#"%#",[arrRoutePoints objectAtIndex:i]);
NSLog(#"Current \n[%g",current.coordinate.latitude);
NSLog(#"%g]",current.coordinate.longitude);
coord[i]=current.coordinate;
NSLog(#"\n[%g",coord[i].latitude);
NSLog(#"%g]",coord[i].longitude);
}
self.objpolyline=[MKPolyline polylineWithCoordinates:coord count:numPoints];
free(coord);
[mapView addOverlay:objpolyline];
[mapView setNeedsDisplay];
}
}

Resources