Reload JSON Feed within a UIView - iphone

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?

Related

How do I set map zoom based on nearest pin to current location

Right now I am setting my region based on users current location. I would like to now set the zoom level so I can see the users current location and the nearest pin that is being pulled in via json.
Not until run time will the app know the number of pins or the locations of said pins.
Here is what I have so far.
#implementation LocationsViewController
#synthesize mapView;
#synthesize locationManager;
#synthesize phone;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
self.title = NSLocalizedString(#"Locations", #"Locations");
self.tabBarItem.image = [UIImage imageNamed:#"locations"];
}
return self;
}
- (void)dealloc
{
[super dealloc];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (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.
}
#pragma mark - View lifecycle
//Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"New latitude: %f", newLocation.coordinate.latitude);
NSLog(#"New longitude: %f", newLocation.coordinate.longitude);
MKCoordinateRegion region;
region.center.latitude =newLocation.coordinate.latitude;
region.center.longitude= newLocation.coordinate.longitude;
region.span.longitudeDelta=0.2;
region.span.latitudeDelta =0.2;
[mapView setRegion:region animated:YES];
[mapView setDelegate:self];
//[locationManager stopUpdatingLocation];
}
-(void)viewDidDisappear:(BOOL)animated
{
[locationManager stopUpdatingLocation];
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[locationManager startUpdatingLocation];
if([self connectedToNetwork] != YES)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"OH NO!" message:#"To get the latest information you need a data or wi-fi connection" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
else
{
[mapView removeAnnotations:mapView.annotations];
NSString *urlString = [NSString stringWithFormat:#"http://www.mywebsite.com/json.json"];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
for(id key in json) {
id value = [json objectForKey:key];
NSString *titlePin = [value valueForKey:#"address"];
NSString *address = [value valueForKey:#"title"];
NSString *latitude = [value valueForKey:#"latitude"];
NSString *longitude = [value valueForKey:#"longitude"];
NSArray* foo = [address componentsSeparatedByString: #":"];
NSString* address2 = [foo objectAtIndex: 0];
phone = [foo objectAtIndex: 1];
double myLatitude = [latitude doubleValue];
double myLongitude = [longitude doubleValue];
MKCoordinateRegion location1;
location1.center.latitude =myLatitude;
location1.center.longitude= myLongitude;
location1.span.longitudeDelta=0.1;
location1.span.latitudeDelta =0.1;
MapAnnotation *ann1 =[[[MapAnnotation alloc] init] autorelease];
ann1.title=[NSString stringWithFormat:#"%#",titlePin];
ann1.subtitle=[NSString stringWithFormat:#"%#",address2];
ann1.phone=[NSString stringWithFormat:#"%#",phone];
ann1.coordinate= location1.center;
[mapView addAnnotation:ann1];
[phone retain];
}
}
}
-(MKAnnotationView *) mapView:(MKMapView *)mapView2 viewForAnnotation:(id<MKAnnotation>)annotation {
if (annotation == mapView2.userLocation) {
return nil;
}else{
MKPinAnnotationView *MyPin=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"current"];
MyPin.pinColor = MKPinAnnotationColorPurple;
UIButton *advertButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
[advertButton setImage:[UIImage imageNamed:#"mapphone"] forState:UIControlStateNormal];
[advertButton addTarget:self action:#selector(button:) forControlEvents:UIControlEventTouchUpInside];
MyPin.rightCalloutAccessoryView = advertButton;
MyPin.draggable = NO;
MyPin.highlighted = YES;
MyPin.animatesDrop=TRUE;
MyPin.canShowCallout = YES;
return MyPin;
}
}
-(void)button:(id)sender {
UIButton *button = (UIButton *)sender;
MKPinAnnotationView *annotationView = (MKPinAnnotationView*)button.superview.superview;
MapAnnotation *mapAnnotation = annotationView.annotation;
UIDevice *device = [UIDevice currentDevice];
if ([[device model] isEqualToString:#"iPhone"] ) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:#"tel:%#",mapAnnotation.phone]]];
} else {
UIAlertView *Notpermitted=[[UIAlertView alloc] initWithTitle:mapAnnotation.phone message:#"Your device doesn't support this feature." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[Notpermitted show];
[Notpermitted release];
}
}
- (BOOL) connectedToNetwork
{
Reachability *r = [Reachability reachabilityWithHostName:#"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
BOOL internet;
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
internet = NO;
} else {
internet = YES;
}
return internet;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#end
I did something similar, but based on two annotations, not the user's location. You should be able to replace mapView.centerCoordinate with mapView.userLocation.coordinate.
in viewForAnnotation:
CLLocation *centerLoc = [[CLLocation alloc] initWithLatitude:mapView.centerCoordinate.latitude longitude:mapView.centerCoordinate.longitude];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:[annotation coordinate].latitude longitude:[annotation coordinate].longitude];
CLLocationDistance distance = [loc2 distanceFromLocation:centerLoc];
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(mapView.centerCoordinate, distance*2, distance*2);
MKCoordinateRegion adjustedRegion = [mapView regionThatFits:viewRegion];
[mapView setRegion:adjustedRegion animated:YES];
Note, this code will re-calc the zoom level each time you add an annotation. You may need to save the distance and only change the map if the new distance is greater than the prior distance.

Reload the Map when we navigate to MapTabBar

I have a tabBarView controller and a TableViewController. When I click on a row I wan to go to another Tab which is UIViewController with Map:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
if(storeName)
[self setMap];
}
- (void) setMap {
NSLog(#"Name:%#\n", storeName);
NSLog(#"Adress:%#\n", storeAddress);
self.indexMapView.delegate = self;
self.indexMapView.showsUserLocation = NO;
self.locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDistanceFilter:kCLDistanceFilterNone];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.indexMapView setShowsUserLocation:YES];
CLLocationCoordinate2D location = [self getLocationFromAddressString:self.storeAddress];
NSLog(#"%g", location.latitude);
MapViewAnnotation *mapAnnotation = [[MapViewAnnotation alloc] initWithTitle:#"Store location" coordinate:location];
[self.indexMapView addAnnotation:mapAnnotation];
}
-(CLLocationCoordinate2D) getLocationFromAddressString:(NSString*) addressStr {
NSLog(#"FFF");
NSString *urlStr = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[addressStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError *error = nil;
NSString *locationStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlStr] encoding:NSUTF8StringEncoding error:&error];
NSArray *items = [locationStr componentsSeparatedByString:#","];
double lat = 0.0;
double lon = 0.0;
if([items count] >= 4 && [[items objectAtIndex:0] isEqualToString:#"200"]) {
lat = [[items objectAtIndex:2] doubleValue];
lon = [[items objectAtIndex:3] doubleValue];
}
else {
NSLog(#"Address, %# not found: Error %#",addressStr, [items objectAtIndex:0]);
}
CLLocationCoordinate2D location;
location.latitude = lat;
location.longitude = lon;
return location;
}
This is how I go to the MapViewController:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
MapViewController *mapViewController = [[MapViewController alloc]init];
[mapViewController setStoreAddress:store.address];
[mapViewController setStoreName:store.name];
[mapViewController viewDidLoad];
[self.tabBarController setSelectedIndex:4];
}
The problem is Map does not get update when I go to the page again. When I tried it with PushSegue, it works. but how can I make it work with TabBar?
Well, it looks like you commented out your call to -setMap, which means that when the view loads, nothing of interest is going to happen. Was that intentional?
I figured out how can I pass the data over tab bars. You can find more descriptions in these links:
iPhone: How to Pass Data Between Several Viewcontrollers in a Tabbar App
Passing a managedObjectContext through to a UITabBarController's views
Also this tutorial is useful.

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];

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.

iPhone MapView interrupted

I have a mapkit / view and it works fine - but I scroll around and after 2 - 10 moves my app crashed... and this only with a "interrupted".
Here is part of my code. I think it's a problem with the background threads and an array release / override problem.
Some background info: I generate a "session" key (MapKey) on mapview startup and save on the serverside a pin. The XML includes only new pins for a faster response and shorter XML.
// Update map when the user interacts with it
- (void)mapView:(MKMapView *)aMapView regionDidChangeAnimated:(BOOL)animated
{
MyAnnotation *annotation = [[MyAnnotation alloc] init];
MyAnnotation *ann = [[MyAnnotation alloc] init];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString *postBody = [[[NSString alloc] initWithFormat:#"single=0&lat=%f&lng=%f&sid=%#", mapView.centerCoordinate.latitude, mapView.centerCoordinate.longitude, [prefs stringForKey:#"MapKey"], [prefs stringForKey:#"MapKey"]] autorelease];
[self performSelectorInBackground:#selector(getMark:) withObject:postBody];
}
// make post and interact with verarbeiten
-(void) getMark:(NSString *)postBody
{
NSAutoreleasePool *ccpool = [[NSAutoreleasePool alloc] init];
NSString *urlStr = [[[NSString alloc] initWithFormat:#"http://URL/get.php"] autorelease];
NSMutableURLRequest *request;
NSData *postData = [postBody dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSURLResponse *response;
NSData *dataReply;
id stringReply;
request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:urlStr]];
[request setHTTPMethod: #"POST"];
[request setHTTPBody:postData];
[request setValue:#"text/xml" forHTTPHeaderField:#"Accept"];
dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
stringReply = (NSString *)[[[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding] autorelease];
[self performSelectorInBackground:#selector(verarbeiten:) withObject:stringReply];
[ccpool release];
}
//generate annotations array with annotations an set it to mapview
-(void) verarbeiten:(NSString *)stringReply
{
NSAutoreleasePool *bbpool = [[NSAutoreleasePool alloc] init];
CXMLDocument *rssParser = [[[CXMLDocument alloc] initWithXMLString:stringReply options:0 error:nil] autorelease];
NSMutableArray* annotations = [[NSMutableArray alloc] init];
NSArray *resultNodes = nil;
resultNodes = nil;
resultNodes = [rssParser nodesForXPath:#"//place" error:nil];
for (CXMLElement *resultElement in resultNodes)
{
MyAnnotation *ann = [[MyAnnotation alloc] init];
ann.title = [[resultElement childAtIndex:3] stringValue];
ann.subtitle = [[resultElement childAtIndex:5] stringValue];
ann.currentPoint = [NSNumber numberWithInt:[[[resultElement childAtIndex:1] stringValue] intValue]];
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = [[[resultElement childAtIndex:9] stringValue] floatValue];
region.center.longitude = [[[resultElement childAtIndex:7] stringValue] floatValue];
ann.coordinate = region.center;
//[mapView addAnnotation:ann ];
[annotations addObject:ann];
}
[mapView addAnnotations:annotations ];
[annotations release];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[bbpool release];
}
- (MKAnnotationView *) mapView:(MKMapView *)mV viewForAnnotation:(MyAnnotation *) annotation
{
MKPinAnnotationView *pinView = nil;
if(annotation != mapView.userLocation)
{
static NSString *defaultPinID = #"de.my.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 = NO;
pinView.userInteractionEnabled = YES;
UIButton *btnVenue = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
btnVenue.tag = [annotation.currentPoint intValue];
[btnVenue addTarget:self action:#selector(showLinks:) forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = btnVenue;
}
else
{
[mapView.userLocation setTitle:#"You are here"];
}
return pinView;
}
#import "MyAnnotation.h"
#implementation MyAnnotation
#synthesize coordinate, title, subtitle,currentPoint;
-(void)dealloc
{
[title release];
[subtitle release];
[super dealloc];
}
#end
#import <Foundation/Foundation.h>
#import <MapKit/MKAnnotation.h>
#interface MyAnnotation : NSObject <MKAnnotation>
{
CLLocationCoordinate2D coordinate;
NSString *title;
NSString *subtitle;
NSNumber *currentPoint;
}
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
#property (nonatomic, copy) NSString *title;
#property (nonatomic, copy) NSString *subtitle;
#property(nonatomic, retain) NSNumber *currentPoint;
#end
Just a thought: since -[MKMapView addAnnotations:] (potentially) performs UI modifications, you may want to call it in the main thread:
[mapView performSelectorOnMainThread: #selector(addAnnotations:) withObject: annotations waitUntilDone: YES];