How to find Latitude and Longitude from Address in iPhone - iphone

I am making one application in which i am getting the address, i need to find the latitude and longitude from that address and show the place in map
- (void)viewDidLoad
{
[super viewDidLoad];
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
mapView.showsUserLocation = YES;
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
geoCoder.delegate = self;
[geoCoder start];
double latitude = 0, longitude = 0;
region.center.latitude = latitude;
region.center.longitude = longitude;
region.span.longitudeDelta = 0.01f;
region.span.latitudeDelta = 0.01f;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
DisplayMap *ann = [[DisplayMap alloc] init];
ann.title = #"BarRestaurant";
ann.subtitle = #"...";
ann.coordinate = region.center;
[mapView addAnnotation:ann];
}
-(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:
(id <MKAnnotation>)annotation {
MKPinAnnotationView *pinView = nil;
if(annotation != mapView.userLocation)
{
static NSString *defaultPinID = #"com.invasivecode.pin";
pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( pinView == nil ) pinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
pinView.pinColor = MKPinAnnotationColorRed;
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
}
else
{
[mapView.userLocation setTitle:#"I am here"];
}
return pinView;
}
- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address
{
appRestaurantAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
double latitude = 0, longitude = 0;
address = delegate.streetName;
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;
return center;
}
however i am unable to find the latitude and longitude please help me where i am doing wrong in the delegate i am getting the address from web server

Try this code,
- (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;
return center;
}
Also refer this link

After ios 5.0, google maps and google maps api should not be used in native mapview. It will violate both google and apple policies.
But we can find the location from apple provided mapkit framework itself.
Please see the below link.
https://developer.apple.com/library/ios/documentation/userexperience/conceptual/LocationAwarenessPG/UsingGeocoders/UsingGeocoders.html
Its very simple using "CLGeocoder" like :
geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:#"1 Infinite Loop"
completionHandler:^(NSArray* placemarks, NSError* error){
for (CLPlacemark* aPlacemark in placemarks)
{
// Process the placemark.
}
}];

Related

Load Map View on MKMapView

I want to load map on MKMapView.
Basically what i want to do is,
I want to load Particular Venue in my MapView.
My Database contains lot of Venues, according to requirement, i am fetching Venue and i want to load that Venue in my mapView.
for eg: I got this as Venue: #"100 Oxford Street, London, W1D 1LL, 020 7636 0933" from Database, then i want to load this location in my mapView
Thanks in advance.
EDIT:
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
NSString *venue= #"100 Oxford Street, London, W1D 1LL, 020 7636 0933";
[geocoder geocodeAddressString:venue completionHandler:^(NSArray *placemarks, NSError *error)
{
if ([placemarks count] > 0)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *loc = placemark.location;
CLLocationCoordinate2D _venue = loc.coordinate;
NSLog(#"_venue:=%f",loc.coordinate);
MKPointAnnotation *venueAnnotation = [[MKPointAnnotation alloc]init];
[venueAnnotation setCoordinate:_venue];
[venueAnnotation setTitle:#"Venue"];
[MapVw addAnnotation:venueAnnotation];
}
}
];
- (IBAction)BtnClick:(id)sender {
NSLog(#"Map ");
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:#"100 Oxford Street, London, W1D 1LL, 020 7636 0933"
completionHandler:^(NSArray* placemarks, NSError* error)
{
if (placemarks && placemarks.count > 0)
{
CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
[self.MapView addAnnotation:placemark];
CLLocationCoordinate2D _venue = placemark.coordinate;
[self.MapView setCenterCoordinate:_venue];
MKCoordinateRegion region = self.MapView.region;
region.span.longitudeDelta = 1.0;
region.span.latitudeDelta = 1.0;
[self.MapView setRegion:region animated:YES];
}
}
];
}
Steps:
1. Import CoreLocation.framework and MapKit.framework.
2. Use CoreLocation class Geocoder's method :
geoCodeAddressString:completionHandler:
NSString *venue= #"100 Oxford Street, London, W1D 1LL, 020 7636 0933";
[_geoCoder geocodeAddressString:venue completionHandler:^(NSArray *placemarks, NSError *error)
{
if ([placemarks count] > 0)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *loc = placemark.location;
CLLocationCoordinate2D _venue = loc.coordinate;
}
});
]
[self performSelector:#selector(createVenueAnnotation) withObject:nil afterDelay:5];
UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc]init];
[_mapView addSubview:activity];
[activity startAnimating];
Step 3. If you want to place a MKPointAnnotation on the venue point.
- (void)createVenueAnnotation{
[activity stopAnimating];
[activity removeFromSuperview];
MKPointAnnotation *venueAnnotation = [[MKPointAnnotation alloc]init];
[venueAnnotation setCoordinate:_venue];
[venueAnnotation setTitle:#"Venue"];
[_mapView addAnnotation:venueAnnotation];
}
Step 4: Center your map around the venue.
// you need to call this function
- (void)centerMapAroundVenue
{
MKMapRect rect = MKMapRectNull;
MKMapPoint venuePoint = MKMapPointForCoordinate(_venue);
rect = MKMapRectUnion(rect, MKMapRectMake(venuePoint .x, venuePoint .y, 0, 0));
MKCoordinateRegion region = MKCoordinateRegionForMapRect(rect);
[_mapView setRegion:region animated:YES];
}
Here is simple scenario :
Get the Co-ordinates of the Address using GeoCoder
Using the Co-ordinatation ,Add the Annotation to the MapView.
Do something Like this to get the CLlocationCoordinate :
- (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;
return center;
}
Using the Center just add the annotation to the MapView.
[self.mapView addAnnotation:<annotationName>];
Plz go through this link For more info.
Hope this helps.

Issue in Displaying Multiple annonations view in MkMapKit

I need to display multiple annonation views in MKMapKit..I use this code..
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib
[mapView setMapType:MKMapTypeStandard];
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
DisplayMap *ann = [[DisplayMap alloc] init];
//NSLog(#"xapp.arrplacename:%d",[xapp.arrplacename count]);
for (i=0;i<=[arrplacename count]-1;i++)
{
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
//arrplacename contains the address of the locations
NSString *straddress=[arrplacename objectAtIndex:i];
NSString *strregion=#"";
NSString *strs=[straddress stringByAppendingString: strregion];
// lbladdress.text=strs;
// NSString add=strs;
// here you define the url setting your address
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",[strs stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
NSLog(#"US: %#",urlString);
// then you get the response string here
NSString *locationString = [[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:urlString]] autorelease];
NSLog(#"loaction strings%#",locationString);
// now you can create an array splitting the response values using the ","
//[listItems addObject:locationString];
listItems = [locationString componentsSeparatedByString:#","];
NSLog(#"A: %#",[xapp.listItems objectAtIndex:2]);
// define latitude and longitude variables
double latitude = 0.0;
double longitude = 0.0;
NSString *strlatitude;
NSString *strlongitude;
strlatitude=[xapp.listItems objectAtIndex:2];
strlongitude=[xapp.listItems objectAtIndex:3];
float stringFloat = [strlatitude floatValue];
float string1Float = [strlongitude floatValue];
// if your array has inside the sctructure you aspect (4 values as described in my previous post) and the first value is like "200" (OK result)
if([xapp.listItems count] >= 4 && [[xapp.listItems objectAtIndex:0] isEqualToString:#"200"])
{
// not sure if you need the accurancy parameter
//accurancy = [[listItems objectAtIndex:1] intValue];
// here you can get your values
// latitude = [[listItems objectAtIndex:2] doubleValue];
//longitude = [[listItems objectAtIndex:3] doubleValue];
latitude = stringFloat;
longitude = string1Float;
}
else {
NSLog(#"Error on map");
}
region.center.latitude = latitude;
region.center.longitude = longitude;
NSLog(#"latitude:%g",region.center.latitude);
// region.center.latitude = 42.7157850;
// region.center.longitude = 27.56470180;
region.span.longitudeDelta = 0.01f;
region.span.latitudeDelta = 0.01f;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
ann.title = [xapp.arrplacename objectAtIndex:i];
ann.subtitle = [xapp.arrplacename objectAtIndex:i];
ann.coordinate = region.center;
[mapView addAnnotation:ann];
}
}
I do have some problems in this code....all the coordnates are not added to the listitems array..I can see only the objects that are added atlast....
This is the delegates I add for displaying the annonation in my map..
- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address{
NSLog(#"ssssss");
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;
return center;
}
-(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:
(id <MKAnnotation>)annotation {
MKPinAnnotationView *pinView = nil;
NSLog(#"pinnview before release %d",[pinView retainCount]);
if (pinView !=nil) {
pinView =nil;
[pinView release];
}
NSLog(#"pinnview after release %d",[pinView retainCount]);
// if it's the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
if(annotation != mapView.userLocation)
{
static NSString *defaultPinID = #"your-pin";
pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( counting < [mapView.annotations count])
{
counting++;
pinView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
/* for(DisplayMap* a in mapView.annotations)
{
if (annotation == a){
pinView.image =
[UIImage imageWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:a.image ofType:nil]];
}
}*/
pinView.centerOffset= CGPointMake(0,-10);
pinView.canShowCallout = YES;
}
}
// return pinView;
}
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
NSLog(#"enter");
[mapView selectAnnotation:[[mapView annotations] lastObject] animated:YES];
}
Delegates are called only once eventhough I'm using [mapView addAnnotation:ann]; inside the for loop...And it shows pin only for the last item tatz added in the array...How can I overcome this????
You are allocating and initializing 'ann' only once before the for loop starts, and you are altering the same and adding it again and again into Map. Thats why you are getting only one annotation.
Move this line inside for loop and try,
DisplayMap *ann = [[DisplayMap alloc] init];

Reload JSON Feed within a UIView

I have a mapView that has annotation added through JSON (feed is stored in NSDictionary). Everything works great, but I want to add a feature.
I want the mapView to reload all of the annotations each time the view reappears (every time the tab bar is pressed). T've tried putting the part where the JSON is added to the NSDictionary in viewWillAppear {} .... but it does not work.
My code is below. Thanks in advance!
#import "MapViewController.h"
#import "DisplayMap.h"
#import "JSON/JSON.h"
#implementation MapViewController
#synthesize mapView;
#synthesize selectedType;
#synthesize locationManager;
// JSON from Server Actions
- (NSString *)stringWithUrl:(NSURL *)url {
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
// Construct a String around the Data from the response
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
- (id)objectWithUrl:(NSURL *)url {
SBJsonParser *jsonParser = [SBJsonParser new];
NSString *jsonString = [self stringWithUrl:url];
// Parse the JSON into an Object
return [jsonParser objectWithString:jsonString error:NULL];
}
- (NSDictionary *) downloadFeed {
id response = [self objectWithUrl:[NSURL URLWithString:#"http://www.example.com/JSON"]];
NSDictionary *feed = (NSDictionary *)response;
return feed;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager startUpdatingLocation];
mapView.mapType = MKMapTypeStandard;
mapView.zoomEnabled = YES;
mapView.scrollEnabled = YES;
mapView.showsUserLocation = YES;
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
region.span.longitudeDelta = 0.005;
region.span.latitudeDelta = 0.005;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
// Download JSON Feed
NSDictionary *feed = [self downloadFeed];
NSArray *streams = (NSArray *)[feed valueForKey:#"stream"];
int Info;
for (Info = 0; Info < streams.count; Info++) {
NSDictionary *stream = (NSDictionary *)[streams objectAtIndex:Info];
NSLog(#"Time: %#", [stream valueForKey:#"Time"]);
NSLog(#"Type: %#", [stream valueForKey:#"Type"]);
NSLog(#"Longitude: %#", [stream valueForKey:#"Longitude"]);
NSLog(#"Latitude: %#", [stream valueForKey:#"Latitude"]);
double lat = [[stream valueForKey:#"Latitude"] doubleValue];
double lon = [[stream valueForKey:#"Longitude"] doubleValue];
NSString *ttype = [[NSString alloc] initWithFormat: #"%#", [stream valueForKey:#"Type"]];
selectedType = ttype;
CLLocationCoordinate2D coord = {lat, lon};
DisplayMap *ann = [[DisplayMap alloc] init];
ann.title = [NSString stringWithFormat: #"%#", [stream valueForKey:#"Type"]];
ann.subtitle = [NSString stringWithFormat: #"%#", [stream valueForKey:#"Time"]];
ann.coordinate = coord;
[mapView addAnnotation:ann];
}
}
}
}
-(void)viewWillAppear { }
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
CLLocationCoordinate2D loc = [newLocation coordinate];
[mapView setCenterCoordinate:loc];
}
-(IBAction)refreshMap:(id)sender {
// Download JSON Feed
NSDictionary *feed = [self downloadFeed];
NSArray *streams = (NSArray *)[feed valueForKey:#"stream"];
int Info;
for (Info = 0; Info < streams.count; Info++) {
NSDictionary *stream = (NSDictionary *)[streams objectAtIndex:Info];
NSLog(#"Time: %#", [stream valueForKey:#"Time"]);
NSLog(#"Type: %#", [stream valueForKey:#"Type"]);
NSLog(#"Longitude: %#", [stream valueForKey:#"Longitude"]);
NSLog(#"Latitude: %#", [stream valueForKey:#"Latitude"]);
double lat = [[stream valueForKey:#"Latitude"] doubleValue];
double lon = [[stream valueForKey:#"Longitude"] doubleValue];
NSString *ttype = [[NSString alloc] initWithFormat: #"%#", [stream valueForKey:#"Type"]];
selectedType = ttype;
CLLocationCoordinate2D coord = {lat, lon};
DisplayMap *ann = [[DisplayMap alloc] init];
ann.title = [NSString stringWithFormat: #"%#", [stream valueForKey:#"Type"]];
ann.subtitle = [NSString stringWithFormat: #"%#", [stream valueForKey:#"Time"]];
ann.coordinate = coord;
[mapView addAnnotation:ann];
}
}
-(MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation {
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil; //return nil to use default blue dot view
static NSString *AnnotationViewID = #"annotationViewID";
MKAnnotationView *annotationView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
if (annotationView == nil) {
annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID] autorelease];
}
annotationView.canShowCallout = YES;
if ([annotationView.annotation.title isEqualToString:#"Selected"]) {
UIImage *pinImage = [UIImage imageNamed:#"icon_selected.png"];
[annotationView setImage:pinImage];
}
annotationView.annotation = annotation;
return annotationView;
}
- (void)dealloc {
[mapView release];
self.adView.delegate = nil;
self.adView = nil;
[super dealloc];
}
#end
From UIViewController.h:
- (void)viewWillAppear:(BOOL)animated;
viewWillAppear is not the same as viewWillAppear:. Perhaps if you override the proper method it might work?
I think more details are needed. If viewWillAppear is not getting called then it is probably something to do with the way you are setting up the views.
These two links should give you some pointers.
How do I have a view controller run updating code when it is brought to the top of the stack of views?
and
What's the proper way to add a view controller to the view hierarchy?

How to draw a route between two locations in a MapView in iPhone?

The below code is implemented it shows current location with blue color blinking and destination location with pin.
Now I need to draw route from my current location to destination location.
I don't know how to configure my current location to destination location to draw route in this code.
//NSString *latlong = [[NSString stringWithFormat:#"%f, %f", currentLocation.latitude, currentLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSString *dlatlong = [[NSString stringWithFormat:#"%f, %f", coordinate.latitude, coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSString *url = [NSString stringWithFormat: #"http://maps.google.com/maps?ll=%#&saddr=%#&daddr=%#",
//latlong, latlong, dlatlong];
//[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
#import "MapViewController.h"
#implementation AddressAnnotation
#synthesize coordinate;
//#synthesize currentLocation;
- (NSString *)subtitle{
//return #"Sub Title";
return [NSString stringWithFormat:#"%lf, %lf", coordinate.latitude, coordinate.longitude];
}
- (NSString *)title{
//return #"Title";
return #"Allure-Exclusive";
//return [NSString stringWithFormat:#"%lf, %lf", coordinate.latitude, coordinate.longitude];
}
-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
coordinate=c;
NSLog(#"%f,%f",c.latitude,c.longitude);
return self;
}
#end
#implementation MapViewController
#synthesize address;
#synthesize currentLocation;
static MapViewController *sharedInstance;
+(MapViewController *)sharedInstance{
#synchronized (self)
{
if (!sharedInstance)
[[MapViewController alloc]init];
}
return sharedInstance;
}
+(id)alloc{
#synchronized(self){
NSAssert(sharedInstance==nil,"Attempted to allocate a second instance of a singleton LocationController.");
sharedInstance = [super alloc];
}
return sharedInstance;
}
-(id)init{
if(self==[super init]){
self.currentLocation=[[CLLocation alloc]init];
locationManager=[[CLLocationManager alloc]init];
locationManager.delegate=self;
[self start];
}
return self;
}
-(void)start{
NSLog(#"Start");
mapView.showsUserLocation=YES;
[locationManager startUpdatingLocation];
}
-(void)stop{
mapView.showsUserLocation=NO;
[locationManager stopUpdatingLocation];
}
-(BOOL)locationKnown{
if (round(currentLocation.speed)==-1)
return NO;
else return YES;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if (abs([newLocation.timestamp timeIntervalSinceDate:[NSDate date]])<120){
self.currentLocation=newLocation;
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
UIAlertView *alert;
alert=[[UIAlertView alloc]initWithTitle:#"Error" message:[error description] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
- (void)locationUpdate:(CLLocation *)location{
[mapView setCenterCoordinate:location.coordinate];
if ([mapView showsUserLocation]==NO)
{[mapView setShowsUserLocation:YES];
}
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
// [self addressLocation];
[super viewDidLoad];
self.title=#"Map-View";
mapView.showsUserLocation=YES;
[self showAddress];
NSLog(#"address is %#",address);
//NSString *latlong = [[NSString stringWithFormat:#"%f, %f", currentLocation.latitude, currentLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSString *dlatlong = [[NSString stringWithFormat:#"%f, %f", coordinate.latitude, coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSString *url = [NSString stringWithFormat: #"http://maps.google.com/maps?ll=%#&saddr=%#&daddr=%#",
//latlong, latlong, dlatlong];
//[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}
-(void)showAddress{
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=0.5f;
span.longitudeDelta=0.5f;
CLLocationCoordinate2D location = [self addressLocation];
region.span=span;
region.center=location;
if(addAnnotation != nil) {
[mapView removeAnnotation:addAnnotation];
[addAnnotation release];
addAnnotation = nil;
}
addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];
[mapView addAnnotation:addAnnotation];
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
}
-(CLLocationCoordinate2D) addressLocation {
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
NSString *locationString=[NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSUTF8StringEncoding error:nil];
NSLog(#"locationString %#",locationString);
NSArray *listItems = [locationString componentsSeparatedByString:#","];
double latitude = 0.0;
double longitude = 0.0;
if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:#"200"])
{
latitude = [[listItems objectAtIndex:2] doubleValue];
longitude = [[listItems objectAtIndex:3] doubleValue];
NSLog(#"listItems %#",[listItems objectAtIndex:2]);
}
else {
//Show error
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;
return location;
}
- (MKAnnotationView *) mapView:(MKMapView *)mapView1 viewForAnnotation:(id <MKAnnotation>) annotation{
if (annotation==mapView.userLocation)
{
mapView1.userLocation.title=#"Current Location";
[mapView1 setRegion:MKCoordinateRegionMakeWithDistance(mapView.userLocation.coordinate, 1000, 1000)animated:YES];
return nil;
}
else {
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorRed;
annView.animatesDrop=YES;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5,5);
return annView;
}
}
//NSString *latlong = [[NSString stringWithFormat:#"%f, %f", currentLocation.latitude, currentLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSString *dlatlong = [[NSString stringWithFormat:#"%f, %f", coordinate.latitude, coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSString *url = [NSString stringWithFormat: #"http://maps.google.com/maps?ll=%#&saddr=%#&daddr=%#",
// latlong, latlong, dlatlong];
//[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Overriden to allow any orientation.
return YES;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// [self stop];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[address release];
[currentLocation release];
[locationManager release];
[super dealloc];
}
#end
There is no feature to draw directions from source to destination in the map view using MKMapKit frame work.
You have to show directions using Google Maps in the iPhone by using the following code.
NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:#"http://maps.google.com/maps?f=d&source=s_d&saddr=%#&daddr=%#&hl=en",[currentLoc stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ,[destLocation stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
[[UIApplication sharedApplication] openURL:url];
If you wrote this code when the directions button clicked. Then the App will close and Google Maps will open and it will shows the direction.
NSString *latlong = [[NSString stringWithFormat:#"%f, %f", mapView.userLocation.location.coordinate.latitude, mapView.userLocation.location.coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *dlatlong = [[NSString stringWithFormat:#"%f, %f",52.366428f,4.896349f] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *url = [NSString stringWithFormat: #"http://maps.google.com/maps?ll=%#&saddr=%#&daddr=%#",
latlong, latlong, dlatlong];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
I went with this code... it shows the destination perfect and userlocation is at 0.000000,0.000000 values.
I need to see current location too.

Load Google Map Directly to specified Address in iPhone

How to load Google Map - Specific area map - specified address by user in UItextField?
Ok. I Got the solution by r&d.
See the code following.
-(IBAction)showAddress // after adding the Address into textField - button pressed{
[addressField resignFirstResponder];
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=0.05;
span.longitudeDelta=0.05;
CLLocationCoordinate2D location = [self addressLocation];
region.span=span;
region.center=location;
if(addAnnotation != nil)
{
[mapView removeAnnotation:addAnnotation];
[addAnnotation release];
addAnnotation=nil;
}
addAnnotation = [ [AddressAnnotation alloc] initWithCoordinate:location];
[mapView setRegion:region animated:TRUE];
[mapView regionThatFits:region];
[mapView addAnnotation:addAnnotation];
}
-(CLLocationCoordinate2D) addressLocation {
// NSString *urlString = [[NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",[addressField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *urlString=[NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",[addressField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
NSArray *listItems = [locationString componentsSeparatedByString:#","];
double latitude=0.0;
double longitude=0.0;
if([listItems count] >=4 && [ [listItems objectAtIndex:0] isEqualToString:#"200"])
{
latitude = [ [listItems objectAtIndex:2] doubleValue];
longitude = [ [listItems objectAtIndex:3] doubleValue];
}
else
{
NSLog(#"Error");
}
CLLocationCoordinate2D location;
location.latitude=latitude;
location.longitude=longitude;
return location;
}