GoogleMap not showing user's current location properly when drawing path overlay - ios

I am using GMSPolyline on google map to show shortest path between two points. This map does not show user's current location properly.
Here is my code. Let me know about the correction that I can make in my code. Thanks in advance.
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
{
/////// If it's a relatively recent event, turn off updates to save power.
CLLocation* location = [locations lastObject];
NSDate* eventDate = location.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 0.5)
{
/////// Update your marker on your map using location.coordinate.latitude
//and location.coordinate.longitude);
NSLog(#"event time=%#",eventDate);
#pragma mark start Point of Polyline Drow
///////////////Logitude 23.03 apvathe darek point tyathe start thay etle polyline Drow thay/////
if (location.coordinate.longitude==23.03)
{
[locationManager stopUpdatingLocation];
}
[mypath addObject:[NSString stringWithFormat:#"%f,%f",location.coordinate.latitude,location.coordinate.longitude]];
GMSMutablePath *path1 = [GMSMutablePath path];
for (int i=0; i<mypath.count; i++)
{
//NSString *str1=mypath[i];
NSArray* foo = [mypath[i] componentsSeparatedByString: #","];
NSString* lat = [foo objectAtIndex: 0];
NSString* longi = [foo objectAtIndex: 1];
[path1 addCoordinate:CLLocationCoordinate2DMake([lat floatValue], [longi floatValue])];
}
GMSPolyline *rectangle = [GMSPolyline polylineWithPath:path1];
rectangle.map = mapView_;
marker.position = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
marker.title = #"Gurukul Road,Ahmedabad";
marker.snippet = #"Gujarat";
marker.map = mapView_;
}
}

you have to be more accurate in case of latitude and longitude you are using there %f and that is not accurate as per values of latitude and longitude use this code...
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
strForCurrentLongitude= [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
strForCurrentLatitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
}
Take Double value instead of float in this line.
[path1 addCoordinate:CLLocationCoordinate2DMake([lat floatValue], [longi floatValue])];

Related

Find the distance between my location and a point in ios

I am using a method to get my location:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
CLLocation *currentLocation = newLocation;
NSLog(#"%#", currentLocation);}
//new method to find the distance
-(void) zoomToNearestSpot: (NSArray *) spot location: (CLLocation *)myLocation
{
myLocation = currentLocation;
spot = chSpot;
for (int i=0; i< spot.count; i++)
{
ChargingSpots *mySpot = [spot objectAtIndex:i];
CLLocation *thePoint = [[CLLocation alloc]initWithLatitude:[mySpot.LocationLat doubleValue] longitude:[mySpot.LocationLong doubleValue]];
CLLocationDistance dist = [myLocation distanceFromLocation:thePoint];
NSLog(#"%f", dist);
you get here **distance** in meter so in assumption **20 miles = 32187 meter**
put condition such like
if(distance <= 32187)
{
// under 20 miles you can add the zoom level
}
else
{
// out of 20 miles
}
}
}
First, I need to show all of the spots on the map by zooming out according to their number then find the nearest spots and zoom in the camera on them in.
you have more the two coordinate
1) current (user Location)
2) another coordinate ..
Here distanceFromLocation: method is use for get distance between two location.
CLLocationDistance distance = [currentLOcation distanceFromLocation:anotherLocation];
for example where you need add the following lines
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
CLLocation *currentLocation = newLocation;
for (int i=0; i<chSpot.count; i++)
{
ChargingSpots *spot = [chSpot objectAtIndex:i];
NSString *locLat = spot.LocationLat;
NSString *locLong = spot.LocationLong;
CLLocation *LocationAtual = [[CLLocation alloc] initWithLatitude: locLat longitude: locLong];
CLLocationDistance distanceBetween = [currentLocation
distanceFromLocation: LocationAtual];
NSString *tripString = [[NSString alloc]
initWithFormat:#"%f",
distanceBetween];
NSLog(#"DIST: %f", tripString);
}
}
you can use this code
1.) CLLocation *loc=[[CLLocation alloc]initWithLatitude:spot.LocationLat longitude:spot.LocationLong];
2.) CLLocationDistance distanceInMeters=[currentLocation distanceFromLocation:loc];
This will help.ThankYou

How to generate my traveled path using CLLocationManager on google map in iOS?

User has to create his own path on google map wherever he move step by step the route is generated.
please have look on my code snippet:
- (void)locationManager:(CLLocationManager )manager didUpdateLocations:(NSArray )locations
{
CLLocation* location1 = [locations lastObject];
if (self.endPointArray == nil)
{
self.endPointArray = [[NSMutableArray alloc]init];
}
NSString *pointString=[NSString stringWithFormat:#"%f,%f",location1.coordinate.latitude,location1.coordinate.longitude];
[self.endPointArray addObject:pointString];
NSLog(#"end point array :%#",self.endPointArray);
GMSMutablePath *path = [GMSMutablePath path];
for (int i=0; i<self.endPointArray.count; i++)
{
NSArray *latlongArray = [[self.endPointArray objectAtIndex:i]componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#","]];
[path addLatitude:[[latlongArray objectAtIndex:0] doubleValue] longitude:[[latlongArray objectAtIndex:1] doubleValue]];
}
if (self.endPointArray.count>2)
{
GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
polyline.strokeColor = [UIColor redColor];
polyline.strokeWidth = 3.0f;
polyline.map = _mapView;
}
}
I have create route with help of above code.but sometimes we get unexpected coordinates from CLLocation. If we are on road (route) it's gives perfect but if we are not on road like in home it gives wrong coordinates
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations lastObject];
NSTimeInterval age = -[location.timestamp timeIntervalSinceNow];
if (age > 120) return; // ignore old (cached) updates
if (location.horizontalAccuracy < 0) return; // ignore invalid updates
if(self.oldLocation == nil)
{
self.oldLocation = location;
return
}
CLLocationDistance distance = [location distanceFromLocation: self.oldLocation];
if (distance >= 10 && location.horizontalAccuracy <=20) //you can change 10 to 20 if you want more frequent updates
{
// add location to path
self.oldLocation = location; // save newLocation for next time
}
}
Try using this code. Its from my project and it works just fine. Use it according to your need. Hope it helps you.

Create MKPolyline with only recent CLLocations

My app loads the user's past polylines and displays them on the map. Then the app starts tracking and a straight line is drawn from the last updated coordinate to the first, thereby connecting the two separate lines when they should be separate (shown here
I want to remove this straight line, so I'm thinking the easiest way would be to discard coordinates that are outside a set time frame (e.g 1 minute), so polylines on the map remain separate. I'm not sure how to do this though... I'm a beginner so any suggestions would be much appreciated!
I use this code when loading the past polyline
(IBAction)didClickLoadCoordinates:(id)sender {
// get a reference to the appDelegate so you can access the global managedObjectContext
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:#"Route"];
NSError *error;
id results = [appDelegate.managedObjectContext executeFetchRequest:request error:&error];
if ([results count]) {
polyLine = (Route *)(results[0]);
NSArray *coordinates = polyLine.coordinates;
int ct = 0;
for (CLLocation *loc in coordinates) {
NSLog(#"location %d: %#", ct++, loc);
}
// this copies the array to your mutableArray
_locationsArray = [coordinates mutableCopy];
}
NSInteger numberOfSteps = _locationsArray.count;
//convert to coordinates array to construct the polyline
CLLocationCoordinate2D clCoordinates[numberOfSteps];
for (NSInteger index = 0; index < numberOfSteps; index++) {
CLLocation *location = [_locationsArray objectAtIndex:index];
CLLocationCoordinate2D coordinate2 = location.coordinate;
clCoordinates[index] = coordinate2;
}
MKPolyline *routeLine = [MKPolyline polylineWithCoordinates:clCoordinates count:numberOfSteps];
[_mapView addOverlay:routeLine];
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
And this code to just normally update the cllocations and make the polyline
//get the latest location
CLLocation *currentLocation = [locations lastObject];
//get latest location coordinates
CLLocationDegrees latitude = currentLocation.coordinate.latitude;
CLLocationDegrees longitude = currentLocation.coordinate.longitude;
CLLocationCoordinate2D locationCoordinates = CLLocationCoordinate2DMake(latitude, longitude);
//zoom map to show users location
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(locationCoordinates, 2000, 2000);
MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:viewRegion];
[_mapView setRegion:adjustedRegion animated:YES];
//store latest location in stored track array
[_locationsArray addObject:currentLocation];
//create cllocationcoordinates to use for construction of polyline
NSInteger numberOfSteps = _locationsArray.count;
CLLocationCoordinate2D coordinates[numberOfSteps];
for (NSInteger index = 0; index < numberOfSteps; index++) {
CLLocation *location = [_locationsArray objectAtIndex:index];
CLLocationCoordinate2D coordinate2 = location.coordinate;
coordinates[index] = coordinate2;
}
MKPolyline *routeLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
[_mapView addOverlay:routeLine];
NSLog(#"%#", _locationsArray);

longitude/latitude values are not correct

i try to catch the longitude and latitude values and to display them in the console (NSLog) for the moment, i have puted the correspondant code in the viewWillAppear method, any way, it's not a big deal, my problem is when i show the view the first time, my console show me that:
latitude: 0.000000
longitude:0.000000
and the second time it shows me that :
latitude : 134217731.444448
longitude : 0.700000
the third time :
latitude : 134217731.444448
longitude : 0.700000
the n time :
latitude : 134217731.444448
longitude : 0.700000
this my code in the viewWillAppear (i'm sure it's logic is pretty right and i'm waiting for your clarification):
-(void)viewWillAppear:(BOOL)animated
{
// locationManager update as location
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"Latitude : %#", latitude);
NSLog(#"Longitude : %#",longitude);
}
note that i work on the iPhone simulator, thx for help :)))
You shouldn't check coordinate here.
Implement locationManager:didUpdateToLocation:fromLocation: method in the same class and check the location inside this method:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
CLLocationCoordinate2D coordinate = [newLocation coordinate];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"Latitude : %#", latitude);
NSLog(#"Longitude : %#",longitude);
}
Your current class should implement CLLocationManagerDelegate protocol, i.e. it should be a delegate of location manager.

longitude and latitude values are both 0.000000 , why?

i use core location to get the longitude and latitude value of my current position and i have displayed it into a label, so for my case it's always 0.000000 for both longitude and latitude, is it because i work on the simulator ??
//longitude and latitude
// locationManager update as location
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
Just initialization the location manager doesn't fetch you values.
you have to write this
[self.locationManager startUpdatingLocation];
then you have to override a callback method
- (void) locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *) newLocation
fromLocation: (CLLocation *) oldLocation {
[self.locationManager stopUpdatingLocation];
NSString *latitude = [NSString stringWithFormat:#"%f", newLocation.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", newLocation.longitude];
[self.locationManager release];
}
Hope that helps!
Shuanak
No. CoreLocation on the iPhone simulator is fixed at 37.3317 North, 122.0307 West (Apple HQ).
Try moving your locationManager code away from your code with the label. Put the location manager code in the viewDidLoad or something and then put this code
CLLocation *location = [locationManager location];
// Configure the new event with information from the location
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
in a function that you call from a button. CoreLocation needs time to get itself going. This is true on the device for sure, but perhaps it is also true on the simulator.

Resources