Showing posts with label MapKit. Show all posts
Showing posts with label MapKit. Show all posts

Tuesday, 11 November 2014

Swift + CLGeocoder to show address string on Map

First of all add & Import MapKit framework in your class.

import UIKit
import MapKit

class ViewController: UIViewControllerCLLocationManagerDelegate
{

    @IBOutlet weak var map: MKMapView!
    
  
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
       self.map.mapType = MKMapType.Standard
       self.map.showsUserLocation = true
        
       self.map.removeAnnotations(self.map.annotations)

     

         let address = "address string"
        
        var geocoder:CLGeocoder = CLGeocoder()
        
        geocoder.geocodeAddressString(address, completionHandler: {(placemarks: [AnyObject]!, error: NSError!) -> Void in
            
            if(error != nil)
            {
                
                println("Error", error)
            }
                
            else if let placemark = placemarks?[0] as? CLPlacemark
            {
                
                var placemark:CLPlacemark = placemarks[0] as CLPlacemark
                var coordinates:CLLocationCoordinate2D = placemark.location.coordinate
                
                var pointAnnotation:MKPointAnnotation = MKPointAnnotation()
                pointAnnotation.coordinate = coordinates
                pointAnnotation.title = "Apple HQ"
                
                self.map.addAnnotation(pointAnnotation)
                self.map.centerCoordinate = coordinates
                self.map.selectAnnotation(pointAnnotation, animated: true)
                
                println("Added annotation to map view")
            }
            
        })

    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
       
    }

}

Monday, 10 November 2014

Swift + Show Current Location and Update Location in a MKMapView

First of all add & Import CoreLocation and MapKit framework in your class.

If you are working with iOS 8 you must include the NSLocationAlwaysUsageDescription key in info.plist file of your current project to get the location services to work.


import UIKit
import CoreLocation

import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate
{

    @IBOutlet weak var map: MKMapView!
    
    let locationManager = CLLocationManager()
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
       self.map.mapType = MKMapType.Standard
       self.map.showsUserLocation = true
        
       self.map.removeAnnotations(self.map.annotations)





        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
        
        
        let location = self.locationManager.location
        
        var latitude: Double = location.coordinate.latitude
        var longitude: Double = location.coordinate.longitude
        
        println("current latitude :: \(latitude)")
        println("current longitude :: \(longitude)")






    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
       
    }


   You have to override CLLocationManager.didUpdateLocations (part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
    {
        //-
        
        let location = locations.last as CLLocation
        
        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
        
        
        self.map.setRegion(region, animated: true)
        
    
        // Add an annotation on Map View
        var point: MKPointAnnotation! = MKPointAnnotation()
        
        point.coordinate = location.coordinate
        point.title = "Current Location"
        point.subtitle = "sub title"
        
        self.map.addAnnotation(point)
        
        //stop updating location to save battery life
        locationManager.stopUpdatingLocation()

    }


//--- Uncomment to add custom annotation view ---//

    /*
    //--- use this code to add custom image (Annotation) for pin point ---//
    func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! 
{
        if !(annotation is MKPointAnnotation)
        {
            return nil
        }
        
        let reuseId = "test"
        
        var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
        
        if anView == nil
        {
            anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
            anView.image = UIImage(named:"1.png")
            anView.canShowCallout = true
        }
        else
        {
            anView.annotation = annotation
        }
        
        return anView
    }
    */



}

Tuesday, 5 August 2014

Get Address from Coordinate or CLLocation


CLLocation *loc = [[CLLocation alloc]initWithLatitude:37.3104 longitude:-122.0108];


[self getAddressFromLocation:loc];



-(void)getAddressFromLocation:(CLLocation*)loc
{
    CLGeocoder *ceo = [[CLGeocoder alloc]init];
    
    
    [ceo reverseGeocodeLocation:loc completionHandler:^(NSArray *placemarks, NSError *error)
     {
         
         NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
         
         
         
         NSLog(@"placemarks=%@",[placemarks objectAtIndex:0]);
         CLPlacemark *placemark1 = [placemarks objectAtIndex:0];
         
         NSLog(@"placemark.ISOcountryCode =%@",placemark1.ISOcountryCode);
         NSLog(@"placemark.country =%@",placemark1.country);
         NSLog(@"placemark.postalCode =%@",placemark1.postalCode);
         NSLog(@"placemark.administrativeArea =%@",placemark1.administrativeArea);
         NSLog(@"placemark.locality =%@",placemark1.locality);
         NSLog(@"placemark.subLocality =%@",placemark1.subLocality);
         NSLog(@"placemark.subThoroughfare =%@",placemark1.subThoroughfare);
         
         
         NSString *locatedaddress = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
         
         //Print the location in the console
         NSLog(@"Currently address is: %@",locatedaddress);
         
         
         if (error == nil && [placemarks count] > 0)
         {
             placemark = [placemarks lastObject];
             
             // strAdd -> take bydefault value nil
             NSString *strAdd = nil;
             
             if ([placemark.subThoroughfare length] != 0)
                 strAdd = placemark.subThoroughfare;
             
             if ([placemark.thoroughfare length] != 0)
             {
                 // strAdd -> store value of current location
                 if ([strAdd length] != 0)
                     strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark thoroughfare]];
                 else
                 {
                     // strAdd -> store only this value,which is not null
                     strAdd = placemark.thoroughfare;
                 }
             }
             
             if ([placemark.postalCode length] != 0)
             {
                 if ([strAdd length] != 0)
                     strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark postalCode]];
                 else
                     strAdd = placemark.postalCode;
             }
             
             if ([placemark.locality length] != 0)
             {
                 if ([strAdd length] != 0)
                     strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark locality]];
                 else
                     strAdd = placemark.locality;
             }
             
             if ([placemark.administrativeArea length] != 0)
             {
                 if ([strAdd length] != 0)
                     strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark administrativeArea]];
                 else
                     strAdd = placemark.administrativeArea;
             }
             
             if ([placemark.country length] != 0)
             {
                 if ([strAdd length] != 0)
                     strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark country]];
                 else
                     strAdd = placemark.country;
             }
             
             
             NSLog(@"Address : %@", strAdd);
             
             
             
             address = strAdd;
             
         }
         
         
     }];
    
}

Show Coordinate on Map View

CLLocationCoordinate2D _coordinate = CLLocationCoordinate2DMake(37.3104, -122.0108);

    MKCoordinateRegion extentsRegion = MKCoordinateRegionMakeWithDistance(_coordinate, 50, 50);
    
    
    extentsRegion.span.latitudeDelta = 0.02f;
    
    extentsRegion.span.longitudeDelta = 0.02f;
    
    extentsRegion.center = _coordinate;
    
    [self.myMapView setRegion:extentsRegion animated:YES];
    
    
    //set annotation
    MKPointAnnotation *annotation = [[MKPointAnnotation alloc]init];
    
    NSString *sttt = [[NSString alloc]initWithFormat:@"%f,%f",_coordinate.latitude,_coordinate.longitude];
    
    
    
    
    annotation.title = [NSString stringWithFormat:@"%@",address];
    annotation.subtitle = sttt;
    
    annotation.coordinate = _coordinate;
    

    [self.myMapView addAnnotation:annotation];

Get Coordinate from Address String Using CLGeocoder and Show on Map with Default Annotation

CLLocationCoordinate2D cordinate = [self geoCodeUsingAddress:@"
6138 Bollinger Road, San Jose, United States"];
    

NSLog(@"coordinate from address::%f , %f",cordinate.longitude,cordinate.latitude);






- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address
{

        CLGeocoder *geocoder11 = [[CLGeocoder alloc] init];
    [geocoder11 geocodeAddressString: address completionHandler:^(NSArray* placemarks, NSError* error){
        for (CLPlacemark* aPlacemark in placemarks)
        {
            // Process the placemark.
            NSString *latDest1 = [NSString stringWithFormat:@"%.4f",aPlacemark.location.coordinate.latitude];
            NSString *lngDest1 = [NSString stringWithFormat:@"%.4f",aPlacemark.location.coordinate.longitude];
           
           
           
           NSLog(@"coordinate from address::%@ , %@",latDest1,lngDest1);
           
           
            CLLocationCoordinate2D center;
            center.latitude = aPlacemark.location.coordinate.latitude;
            center.longitude = aPlacemark.location.coordinate.longitude;
            
            

            
            MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(center, 50, 50);
            
            region.span.latitudeDelta = 0.02f;
            
            region.span.longitudeDelta = 0.02f;
            
            region.center = center;
            
            
            [self.myMapView setRegion:region animated:YES];
            
            
            
            
            
            //set annotation
            MKPointAnnotation *annotation = [[MKPointAnnotation alloc]init];
            
            NSString *sttt = [[NSString alloc]initWithFormat:@"%f,%f",center.latitude,center.longitude];
            
            annotation.titleaddress;
            annotation.subtitle = sttt;
            
            annotation.coordinate = center;
            
            [self.myMapView addAnnotation:annotation];

           
           return center;
           
           
        }
    }];


}

Get Coordinate from Address String Using Google Api and Show on Map with Default Annotation

CLLocationCoordinate2D cordinate = [self geoCodeUsingAddress:@"Your Address"];
    

   
NSLog(@"coordinate from address::%f , %f",cordinate.longitude,cordinate.latitude);








- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address
{
    double latitude = 0, longitude = 0;
    
    NSString *esc_addr =  [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    NSString *req = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];
    
    
    
    NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
    
    
    
    
    if (result)
    {
        NSScanner *scanner = [NSScanner scannerWithString:result];
        if ([scanner scanUpToString:@"\"lat\" :" intoString:nil] && [scanner scanString:@"\"lat\" :" intoString:nil]) {
            [scanner scanDouble:&latitude];
            if ([scanner scanUpToString:@"\"lng\" :" intoString:nil] && [scanner scanString:@"\"lng\" :" intoString:nil]) {
                [scanner scanDouble:&longitude];
            }
        }
    }
    CLLocationCoordinate2D center;
    center.latitude = latitude;
    center.longitude = longitude;
    
    
    
    
    
    
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(center, 50, 50);
    
    region.span.latitudeDelta = 0.02f;
    
    region.span.longitudeDelta = 0.02f;
    
    region.center = center;
    
    
    [self.myMapView setRegion:region animated:YES];
    
    
    
    
    
    //set annotation
    MKPointAnnotation *annotation = [[MKPointAnnotation alloc]init];
    
    NSString *sttt = [[NSString alloc]initWithFormat:@"%f,%f",center.latitude,center.longitude];
    
    annotation.title = address;
    annotation.subtitle = sttt;
    
    annotation.coordinate = center;
    
    [self.myMapView addAnnotation:annotation];


    
    
    
    
    return center;
}




You will get the result like this
{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Coimbatore",
               "short_name" : "Coimbatore",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Coimbatore",
               "short_name" : "Coimbatore",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Tamil Nadu",
               "short_name" : "TN",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Coimbatore, Tamil Nadu, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 11.14356120,
                  "lng" : 77.1133590
               },
               "southwest" : {
                  "lat" : 10.89792370,
                  "lng" : 76.8830110
               }
            },
            "location" : {
               "lat" : 11.01684450,
               "lng" : 76.95583209999999
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 11.09502970,
                  "lng" : 77.05123890
               },
               "southwest" : {
                  "lat" : 10.89792370,
                  "lng" : 76.8830110
               }
            }
         },
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}