7

I can already find the current location using latitude and longitude, but I would also like to be able to find the current location given a zip code.

Here is what I have so far:

.h

#import <MapKit/MapKit.h>
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>


@interface ViewController : UIViewController<CLLocationManagerDelegate>

{

CLLocationManager *locationManager;
 CLLocation *currentLocation;

    IBOutlet UILabel *label1;
    IBOutlet UILabel *lable2;

}
@property (weak, nonatomic) IBOutlet MKMapView *myMapview;
@property (weak, nonatomic) IBOutlet UILabel *label2;
@property (weak, nonatomic) IBOutlet UILabel *lable1;
@end

.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad

{

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    locationManager = [[CLLocationManager alloc]init];



    locationManager.delegate = self;


    locationManager.distanceFilter = kCLDistanceFilterNone;


    locationManager.desiredAccuracy = kCLLocationAccuracyBest;


    [locationManager startUpdatingLocation];


    _myMapview.showsUserLocation = YES;

    [self->locationManager startUpdatingLocation];



    CLLocation *location = [locationManager location];


    CLLocationCoordinate2D coordinate = [location coordinate];


    NSString *latitude = [NSString stringWithFormat:@"%f", coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"%f", coordinate.longitude];

    //NSLog(@”dLatitude : %@”, latitude);
    //NSLog(@”dLongitude : %@”,longitude);
    NSLog(@"MY HOME :%@", latitude);
    NSLog(@"MY HOME: %@ ", longitude);

}

#pragma mark CLLocationManager Delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    currentLocation = [locations objectAtIndex:0];
    [locationManager stopUpdatingLocation];

    [self->locationManager stopUpdatingLocation];




    NSLog(@"my latitude :%f",currentLocation.coordinate.latitude);

    NSLog(@"my longitude :%f",currentLocation.coordinate.longitude);
    label1.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
    lable2.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];


    NSLog(@"Detected Location : %f, %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
    CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
    [geocoder reverseGeocodeLocation:currentLocation
                   completionHandler:^(NSArray *placemarks, NSError *error)
     {
                       if (error)
                       {
                           NSLog(@"Geocode failed with error: %@", error);
                           return;
                       }

NSLog(@"Monday");
                       CLPlacemark *placemark = [placemarks objectAtIndex:0];
                       NSLog(@"placemark.ISOcountryCode %@",placemark.ISOcountryCode);

                   }];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"didUpdateToLocation: %@", newLocation);
    CLLocation *currentLocation = newLocation;

    if (currentLocation != nil)
    {

    label1.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
    lable2.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
Jordan Gray
  • 16,306
  • 3
  • 53
  • 69
  • Your phrasing is confusing. You say you want to find the user's "current" location based on zip code. However, if you specify an arbitrary zip code then you don't want the user's CURRENT location, you want to calculate a location for a zip code. Those are different things. – Duncan C Feb 04 '14 at 13:48

4 Answers4

22

Step 1: Import MobileCoreServices framework in .h File

#import <MobileCoreServices/MobileCoreServices.h>

Step 2: Add delegate CLLocationManagerDelegate

@interface yourViewController : UIViewController<CLLocationManagerDelegate>
{
    CLLocationManager *locationManager;
    CLLocation *currentLocation;
}

Step 3: Add this code in class file

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self CurrentLocationIdentifier]; // call this method
}

Step 4: Method to get location

//------------ Current Location Address-----
-(void)CurrentLocationIdentifier
{
    //---- For getting current gps location
    locationManager = [CLLocationManager new];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];
    //------
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    currentLocation = [locations objectAtIndex:0];
    [locationManager stopUpdatingLocation];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
     {
         if (!(error))
         {
             CLPlacemark *placemark = [placemarks objectAtIndex:0];
            NSLog(@"\nCurrent Location Detected\n");
             NSLog(@"placemark %@",placemark);
             NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
             NSString *Address = [[NSString alloc]initWithString:locatedAt];
             NSString *Area = [[NSString alloc]initWithString:placemark.locality];
             NSString *Country = [[NSString alloc]initWithString:placemark.country];
             NSString *CountryArea = [NSString stringWithFormat:@"%@, %@", Area,Country];
             NSLog(@"%@",CountryArea);
         }
         else
         {
             NSLog(@"Geocode failed with error %@", error);
             NSLog(@"\nCurrent Location Not Detected\n");
             //return;
             CountryArea = NULL;
         }
         /*---- For more results 
         placemark.region);
         placemark.country);
         placemark.locality); 
         placemark.name);
         placemark.ocean);
         placemark.postalCode);
         placemark.subLocality);
         placemark.location);
          ------*/
     }];
}
Rajesh Loganathan
  • 11,129
  • 4
  • 78
  • 90
  • 5
    Your post is a good explanation of how to figure out the zip code of the user's current location. However, the user is asking for the opposite - how to find a location based on a zip code. That requires forward geocoding, not reverse geocoding. – Duncan C Feb 04 '14 at 13:47
  • @SVM-RAjESH thk for answered i will try –  Feb 04 '14 at 13:47
  • @DuncanC : User tried to get address from current location. But title only asked to get from zip code. – Rajesh Loganathan Feb 04 '14 at 13:53
  • @Duncan C get some location using Zip code is possible or NOT –  Feb 04 '14 at 14:09
  • @SVM-RAJESH, Why do you need to import MobileCoreServices? –  Feb 04 '14 at 14:51
  • Note that placemark locality can be nil in unincorporated areas. This can crash creating a string with this value. – ahwulf Feb 04 '14 at 15:13
  • @PavanAlapati, yes it is possible to get a location using only a zip code. Is that what you are trying to do? – Duncan C Feb 04 '14 at 18:26
  • 1
    whats #import is for. for cllocationmanager you need cllocation framework. in reversegeocode function, you should enumerate each placemark object, not only first object. – Pawan Rai Feb 04 '14 at 19:18
  • @Duncan C yes i want get a location using a Zip code if u have code plz upload that code thanks in advanced –  Feb 05 '14 at 10:09
  • 1
    @PavanAlapati, you want to use the CLGeocoder method geocodeAddressString. See if you can figure it out without me spoon-feeding you code. – Duncan C May 29 '14 at 12:34
6

Here is a code to get user current location using block

1) #import <CoreLocation/CoreLocation.h>

2) <CLLocationManagerDelegate>

3) in .h file

//Location
typedef void(^locationBlock)();

//Location
-(void)GetCurrentLocation_WithBlock:(void(^)())block;

@property (nonatomic, strong) locationBlock _locationBlock;
@property (nonatomic,copy)CLLocationManager *locationManager;
@property (nonatomic)CLLocationCoordinate2D coordinate;
@property (nonatomic,strong) NSString *current_Lat;
@property (nonatomic,strong) NSString *current_Long;

4) in .m file

#pragma mark - CLLocationManager
-(void)GetCurrentLocation_WithBlock:(void(^)())block {
    self._locationBlock = block;
    _locationManager = [[CLLocationManager alloc] init];
    [_locationManager setDelegate:self];
    [_locationManager setDistanceFilter:kCLDistanceFilterNone];
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    if (IS_OS_8_OR_LATER) {
        if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [_locationManager requestWhenInUseAuthorization];
            [_locationManager requestAlwaysAuthorization];
        }
    }
    [_locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *currentLoc=[locations objectAtIndex:0];
    _coordinate=currentLoc.coordinate;
    _current_Lat = [NSString stringWithFormat:@"%f",currentLoc.coordinate.latitude];
    _current_Long = [NSString stringWithFormat:@"%f",currentLoc.coordinate.longitude];
    NSLog(@"here lat %@ and here long %@",_current_Lat,_current_Long);
    self._locationBlock();
    [_locationManager stopUpdatingLocation];
    _locationManager = nil;
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
}

5) Call function

- (void)viewDidLoad {
    [super viewDidLoad];
    [self GetCurrentLocation_WithBlock:^{
        NSLog(@"Lat ::%f,Long ::%f",[self.current_Lat floatValue],[self.current_Long floatValue]);
    }];
}

6) And add below line to .plist

Any one or both of below keys needs to be added in Info.plist file.

NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
Hardik Thakkar
  • 15,269
  • 2
  • 94
  • 81
0

You can call Google APIs Maps service to get the location using zipcode:

Just enter your zipcode in address={your zipcode}.

Bista
  • 7,869
  • 3
  • 27
  • 55
Ajay
  • 1,622
  • 20
  • 36
  • my code displayed only in Console but not in map that is Simulator –  Feb 05 '14 at 10:12
  • off course you have to display that location in the map yourself. – Ajay Feb 05 '14 at 10:19
  • k but longitude and latitude data Double type but i don't no how to pass NSDictionsary values into Double Variable –  Feb 05 '14 at 10:43
  • First you have to parse the whole JSON response and get the values from that. – Ajay Feb 05 '14 at 10:44
  • if you adder stand my code and then plz find that solution 7 location display on MAP –  Feb 05 '14 at 11:14
  • @ahay are you get my code or Not if you adder stand my code and then plz find that solution 7 location display on MAP –  Feb 05 '14 at 11:34
  • 7 location display? I am not getting you. – Ajay Feb 05 '14 at 11:36
0

if location permissions not asking when you first launch then you cant get your current location .

iOS8 has got us major API changes with the LocationsServices

Assuming [CLLocationManager locationServicesEnabled] return YES,

With the First Launch of the iOS App [both iOS7 and iOS8] - locationMangers(CLLocationManager)

Jagveer Singh
  • 2,258
  • 19
  • 34