Im doing an app in which i have to find the current location of the user.can i get the current location of the user in the iOS 5 simulator by using CLLocationmanager?
xcode - Edit Scheme - Run you.app - Option
check Allow Location Simulation, then select "Default Location"
Add GPX File to Project
the format like this
In Xcode, you can select the location to simulate using a small button above the console.
- (void)viewDidLoad{
[super viewDidLoad];
self.title = #"MapView";
self.navigationController.navigationBarHidden = NO;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
- (void) loadPin {
iCodeBlogAnnotation *appleStore1;
CLLocationCoordinate2D workingCoordinate;
workingCoordinate.latitude = [latitude doubleValue];
workingCoordinate.longitude = [longitude doubleValue];
appleStore1 = [[iCodeBlogAnnotation alloc] initWithCoordinate:workingCoordinate];
[appleStore1 setTitle:[NSString stringWithFormat:#"Default Point"]];
//[appleStore1 setSubtitle:[NSString stringWithFormat:#"Distance %.2f Miles",miles]];
[appleStore1 setAnnotationType:iCodeBlogAnnotationTypeEDU];
[mapView addAnnotation:appleStore1];
[(MKMapView*)self.mapView selectAnnotation:appleStore1 animated:NO];
MKCoordinateRegion region;
region.center.latitude = [latitude doubleValue];
region.center.longitude = [longitude doubleValue];
region.span.latitudeDelta = .5;
region.span.longitudeDelta = .5;
[mapView setRegion:region animated:YES];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
latitude = [[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.latitude];
longitude = [[NSString alloc] initWithFormat:#"%f", newLocation.coordinate.longitude];
[locationManager stopUpdatingLocation];
if (latitude > 0) {
[self loadPin];
}
}
Related
In my application i have used the MKmapview,I want to hide the user current location annotation point,Here my code
- (void)viewDidLoad
{
[super viewDidLoad];
appDel=(AppDelegate *)[UIApplication sharedApplication].delegate;
DatabaseController *dbObj=[[DatabaseController alloc] init];
NSString *query=[NSString stringWithFormat:#"select * from petBoundarySettings where petId=%#",self.petID];
NSMutableArray *alertSettingArray=[dbObj getPetAlertSerrings:query :[appDel getDBPath]];
if([alertSettingArray count]>0){
distance=[[[alertSettingArray objectAtIndex:0] objectForKey:#"distance"] integerValue];
address=[[alertSettingArray objectAtIndex:0] objectForKey:#"address"];
lat2=[[alertSettingArray objectAtIndex:0] objectForKey:#"lat"] ;
lon2=[[alertSettingArray objectAtIndex:0] objectForKey:#"lang"] ;
}
UIImageView *imageNav = [[UIImageView alloc] initWithImage: [UIImage imageNamed: #"sml-cat_03.png"]];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:imageNav];
[imageNav release];
[dbObj release];
MKCoordinateSpan span;
span.latitudeDelta=.01;
span.longitudeDelta=.01;
MKCoordinateRegion region;
//distance=appDel.alertDistance;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = nil;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
currentAnnotation=[[MyAnnotations alloc]init];
NSLog(#"GL%f",appDel.getlat);
NSLog(#"GN%f",appDel.getlon);
regionCoordinate.latitude =[lat2 floatValue];
regionCoordinate.longitude = [lon2 floatValue];
currentAnnotation.coordinate=regionCoordinate;
currentAnnotation.title=#"Boundary Location";
currentAnnotation.subtitle=appDel.address;
region.center=CLLocationCoordinate2DMake(regionCoordinate.latitude,regionCoordinate.longitude);
region.span=span;
[_myMapView setRegion:region animated:YES];
[_myMapView regionThatFits:region];
region1=region;
petAnnotation=[[MyAnnotations alloc]init];
petCoordinate.latitude = +11.028549739;
petCoordinate.longitude = +76.89644586;
petAnnotation.coordinate=petCoordinate;
petAnnotation.title=#"My Pet Location";
petAnnotation.subtitle=#"Vadavalli";
MKCircle *circle = [MKCircle circleWithCenterCoordinate:regionCoordinate radius:distance];
[_myMapView addOverlay:circle];
CLLocation *whereIAm = [locationManager location];
NSLog(#"MI%#",whereIAm);
[_myMapView addAnnotation:currentAnnotation];
MKMapPoint p1 = MKMapPointForCoordinate(regionCoordinate);
MKMapPoint p2 = MKMapPointForCoordinate(petCoordinate);
CLLocationDistance dist = MKMetersBetweenMapPoints(p1, p2);
i=0;
[self getPetData];
timer= [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:#selector(getPetData) userInfo:nil repeats:YES];
if(appDel.checkGPS==NO)
{
[self getPetDataFromGPS];
}
}
How to hide the current location from mkmapview,Please help me to sort out.
MKMapView has a property named showsUserLocation that you can set to determine whether the user's location can be displayed. However, I see that you're not setting it in code, and the default value is NO.
If you're using a Xib or Storyboard, check the MKMapView in there, as there is a checkbox for this behaviour in the attributes inspector. (Shows User Location)
Here is my goal:
I have to show the user location with his address on a map every time he open the view that has the MapView and then stop location to save battery. So far i can do it, but if the user moves to another area and enter the view (after leave it) the location does not change.
Here is my code:
- (void)viewDidLoad
{
mapView.mapType = MKMapTypeStandard;
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[super viewDidLoad];
}
- (void)viewDidAppear:(BOOL)animated{
if(!self.locationManager){
self.locationManager = [[CLLocationManager alloc] init];
}
[self.locationManager startUpdatingLocation];
}
-(void)viewDidDisappear:(BOOL)animated{
self.locationManager = nil;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
MKCoordinateRegion viewRegion =
MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 2000, 2000);
MKCoordinateRegion adjustedRegion = [mapView regionThatFits:viewRegion];
[mapView setRegion:adjustedRegion animated:YES];
[manager stopUpdatingLocation];
MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc]
initWithCoordinate:newLocation.coordinate];
geocoder.delegate = self;
[geocoder start];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
MapLocation *annotation = [[MapLocation alloc] init];
annotation.streetAddress = placemark.thoroughfare;
annotation.city = placemark.locality;
annotation.state = placemark.administrativeArea;
annotation.zip = placemark.postalCode;
annotation.coordinate = geocoder.coordinate;
[mapView addAnnotation:annotation];
geocoder.delegate = nil;
}
- (void)openCallout:(id<MKAnnotation>)annotation {
[mapView selectAnnotation:annotation animated:YES];
}
- (MKAnnotationView *) mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>) annotation {
static NSString *placemarkIdentifier = #"Map Location Identifier";
if ([annotation isKindOfClass:[MapLocation class]]) {
MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[theMapView dequeueReusableAnnotationViewWithIdentifier:placemarkIdentifier];
if (annotationView == nil) {
annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:placemarkIdentifier];
}
else{
annotationView.annotation = annotation;
}
annotationView.enabled = YES;
annotationView.canShowCallout = YES;
annotationView.image = [UIImage imageNamed:#"rescue"];
[self performSelector:#selector(openCallout:) withObject:annotation afterDelay:0.5];
return annotationView;
}
return nil;
}
I have a CLLocationManager on another view that get user location without a map (here the location is working just fine). If a start the location on that view and go back to the view with the map it's is updated. Why that?
Any ideias?
- (void)loadView {
MKMapView *mv = [[MKMapView alloc]init];
mapView.showsUserLocation=YES;
mv.delegate=self;
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
[mapView setCenterCoordinate:mapView.userLocation.location.coordinate animated:YES];
mapView.showsUserLocation=NO;
}
well to display it on the map
MKMapView *mv = [[MKMapView alloc]init];
CLLocationCoordinate2D c = CLLocationCoordinate2DMake(locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude);
[mv setCenterCoordinate:c animated:YES];
and to stop updating
[locationManager stopUpdatingLocation];
I am trying to get current location of user using CLLocationCoordinate2D. I want the values in the format like
CLLocationCoordinate2D start = {-28.078694,153.382844 };
So that I can use them like following:
NSString *urlAddress = [NSString
stringWithFormat:#"http://maps.google.com/?saddr=%1.6f,%1.6f&daddr=%1.6f,%1.6f",
start.latitude, start.longitude,
destination.latitude, destination.longitude];
I used
CLLocation *location = [[CLLocation alloc]init ];
CLLocationDegrees currentLatitude = location.coordinate.latitude;
CLLocationDegrees currentLongitude = location.coordinate.longitude;
to get current lat & long.
But I am getting 0.000 for both when I try to test. I am testing on iPhone 4s.
If there is any sample code, it will be great.
Add CoreLocation framework first and then use the following code...and your viewController must implement CLLocationManagerDelegate
-(void)findCurrentLocation
{
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
if ([locationManager locationServicesEnabled])
{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
NSString *str=[[NSString alloc] initWithFormat:#" latitude:%f longitude:%f",coordinate.latitude,coordinate.longitude];
NSLog(#"%#",str);
}
in AppDelegate.h declare following variable. and implement
CLLocationManagerDelegate delegate.
CLLocationManager *locationManager;
CLLocation *currentLocation;
in AppDelegate.h.m file write following code.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
self.currentLocation = newLocation;
self.currentLat = newLocation.coordinate.latitude;
self.currentLong = newLocation.coordinate.longitude;
}
You need to use CLLocationManager to get a user's location. CLLocation is only a class of objects used to represent locations, it can't get user location by it self.
For more details and example, please follow to Apple docs on Location Awareness Programming.
CLLocationCoordinate2D location = [[[mapview userLocation] location] coordinate];
NSLog(#"Location found from Map: %f %f",location.latitude,location.longitude);
and also refer the link(without mapview0
https://developer.apple.com/library/ios/#samplecode/LocateMe/Introduction/Intro.html
use location manager to get lat and long, follow this tutorial for sample code http://www.edumobile.org/iphone/miscellaneous/how-to-get-current-latitude-and-longitude-in-iphone/
-(void)findCurrentLocation
{
if ([CLLocationManager locationServicesEnabled])
{
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
[self setLocation:[[manager location] coordinate]];
}
I am Showing Australia continent when my Map application launch. I have one button on which I want to set coding for current location and zoom in to that location after pressing butoon. I am getting current latitude & longitude and able to pass in Web-service url. I did following coding
- (void)viewDidLoad
{
//to set the australia region
CLLocationCoordinate2D AusLoc = {-19.048230,133.685730};
MKCoordinateSpan AusSpan = MKCoordinateSpanMake(45, 45);
MKCoordinateRegion AusRegion = MKCoordinateRegionMake(AusLoc, AusSpan);
mapView.region = AusRegion;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation]; }
and
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if((fabs(newLocation.coordinate.latitude) > 0.001) || (fabs(newLocation.coordinate.longitude) > 0.001)) {
NSLog(#"Got location %f,%f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
if (currentLocation != nil) {
[currentLocation release];
}
currentLocation = newLocation;
[currentLocation retain];
}
NSString *lati=[NSString stringWithFormat:#"%f", newLocation.coordinate.latitude];
NSString *longi=[NSString stringWithFormat:#"%f", newLocation.coordinate.longitude];
}
on Search button(web service calling)
NSString *url = [NSString stringWithFormat:#"http://.....url...../hespdirectory/phpsqlsearch_genxml.php?lat=%f&lng=%f&radius=%f",locationManager.location.coordinate.latitude,locationManager.location.coordinate.longitude,radius];
Updated with coding:
- (IBAction) showAddress {
if (locationManager.location == nil)
{
NSLog(#"user location not found yet or service disabled/denied");
}
else
{
// Change map region using span (degrees)...
MKCoordinateSpan span = MKCoordinateSpanMake(0.001, 0.001);
MKCoordinateRegion region = MKCoordinateRegionMake
(locationManager.location.coordinate, span);
[mapView setRegion:region animated:YES];
}
}
When I set mapView.showUserLocation = YES; it shows current location when map application launch that is before tapping button. I am confused with previous answer. So What code should I put under button click event to show current location and also suggest If there is any change to pass current Lati and longi in web service url after giving coding for click event. Thanks in advance
Edited:-
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation
{
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#""];
annView.pinColor = MKPinAnnotationColorGreen;
//annView.animatesDrop=TRUE;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
annView.enabled = YES;
annView.image = [UIImage imageNamed:#"flagg.png"];
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self
action:#selector(showDetails:)
forControlEvents:UIControlEventTouchUpInside];
annView.rightCalloutAccessoryView = rightButton;
NSLog(#"Created annotation at: %f %f", ((CustomPlacemark*)annotation).coordinate.latitude, ((CustomPlacemark*)annotation).coordinate.longitude);
[annView addObserver:self
forKeyPath:#"selected"
options:NSKeyValueObservingOptionNew
context:#"GMAP_ANNOTATION_SELECTED"];
[annView autorelease];
return annView;
}
//return nil;
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context{
NSString *action = (NSString*)context;
// We only want to zoom to location when the annotation is actaully selected. This will trigger also for when it's deselected
if([[change valueForKey:#"new"] intValue] == 1 && [action isEqualToString:#"GMAP_ANNOTATION_SELECTED"])
{
if([((MKAnnotationView*) object).annotation isKindOfClass:[CustomPlacemark class]])
{
CustomPlacemark *place = ((MKAnnotationView*) object).annotation;
// Zoom into the location
[mapView setRegion:place.coordinateRegion animated:TRUE];
NSLog(#"annotation selected: %f %f", ((MKAnnotationView*) object).annotation.coordinate.latitude, ((MKAnnotationView*) object).annotation.coordinate.longitude);
}
}
}
In Search button(calling webservice)
CLLocationCoordinate2D location;
//currentLocation = newLocation;
float radius = [[arrayNo objectAtIndex:[pickerView selectedRowInComponent:0]] floatValue];
//NSURL *url = [[NSURL alloc] initWithString:#"http://www.hettich.com.au/hespdirectory/phpsqlsearch_genxml.php?lat=-33.853468&lng=150.94042160000004&radius=5"];
NSString *url = [NSString stringWithFormat:#"http://www.hettich.com.au/hespdirectory/phpsqlsearch_genxml.php?lat=%f&lng=%f&radius=%f",locationManager.location.coordinate.latitude,locationManager.location.coordinate.longitude,radius];
//NSLog(#"NSString *url");
NSLog(#"%#", url);
NSURL *URL = [NSURL URLWithString:url];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:URL];
//Initialize the delegate.
XMLParser *parser = [[XMLParser alloc] initXMLParser];
//Set delegate
[xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
if(success)
{ resultButton.userInteractionEnabled = YES;
// NSMutableArray* annotations = [[NSMutableArray alloc] init];
for (int i = 0; i < [appDelegate.markers count]; i++)
{
marker *aMarker = [appDelegate.markers objectAtIndex:i];
location.latitude = [aMarker.lat floatValue];
location.longitude =[aMarker.lng floatValue];
AddressAnnotation *annob = [[AddressAnnotation alloc] initWithCoordinate:location];
annob.title = aMarker.name;
annob.subTitle = aMarker.address;
[mapView addAnnotation:annob];
[annob release];
CLLocationCoordinate2D ausLoc = {location.latitude,location.longitude}; //for zoom in the showroom results region
MKCoordinateSpan ausSpan = MKCoordinateSpanMake(0.108889, 0.169922);
MKCoordinateRegion ausRegion = MKCoordinateRegionMake(ausLoc, ausSpan);
NSLog(#"No Errors");
mapView.region = ausRegion;
}
}
In your button tapped method, you should first check if the location manager has obtained a location and then set the map's center or region to the user's location:
if (locationManager.location == nil)
{
NSLog(#"user location not found yet or service disabled/denied");
}
else
{
// Change map center (preserving current zoom level)...
[mapView setCenterCoordinate:locationManager.location.coordinate animated:YES];
// --OR--
// Change map region using distance (meters)...
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance
(locationManager.location.coordinate, 1000, 1000);
[mapView setRegion:region animated:YES];
// --OR--
// Change map region using span (degrees)...
MKCoordinateSpan span = MKCoordinateSpanMake(0.001, 0.001);
MKCoordinateRegion region = MKCoordinateRegionMake
(locationManager.location.coordinate, span);
[mapView setRegion:region animated:YES];
}
In the didUpdateToLocation method, you are setting a "currentLocation" variable but I don't see a need for it. The locationManager already has a location property.
In any case, only considering absolute latitudes or longitudes greater than 0.001 as "valid" is incorrect because a) it excludes locations near the equator or prime meridian (even though you're only interested in Australia this logic is the wrong way to go), and b) it's better instead to check if newLocation itself is nil.
i want my app to get the exact location (longitude and latitude) of where he is as every second, it is possible ? i have this code so far, every 3 second the app get the current location but it doesnt update if i move...
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
NSLog(#"lol");
[locationManager stopUpdatingLocation];
if (wtf == 2) {
[[NSUserDefaults standardUserDefaults] setObject:newLocation forKey:#"old"];
NSLog(#"wtf");
wtf =0;
}
oldLocation = [[NSUserDefaults standardUserDefaults] objectForKey:#"old"];
double rep = [oldLocation distanceFromLocation:newLocation];
NSString *label1 = [NSString stringWithFormat:#"%2.90f",oldLocation.coordinate.latitude];
NSString *label2 = [NSString stringWithFormat:#"%2.90f",newLocation.coordinate.latitude];
if ([label1 isEqual:label2]) {
NSLog(#"penis");
}
labelm.text = label1;
labelkm.text = label2;
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
}
-(void)actualise{
[locationManager startUpdatingLocation];
}
- (void)viewDidLoad {
[super viewDidLoad];
wtf = 2;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:#selector(actualise) userInfo:nil repeats:YES];
}
/*
Use this code to initialize and start the location manager:
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[locationManager startUpdatingLocation];
And implement didUpdateToLocation like this:
- (void) locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*) oldLocation
{
// This will be called every time the device has any new location information.
}
There is no need to use any timers.