Reload the Map when we navigate to MapTabBar - iphone

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.

Related

Custom Pin in Mapkit

I am primarily a JAVA programmer but took on a bus tracker project for the iPhone, so I am not very comfortable with this yet. Please forgive any noobish mistakes. The following code is how it was when I got pins to work. Any changes I made to attempt showing images has been removed.
#import "UICBus_FirstViewController.h"
#interface UICBus_FirstViewController ()
#end
#implementation UICBus_FirstViewController
#synthesize timer;
- (void)viewDidLoad
{
[super viewDidLoad];
CLLocationCoordinate2D zoomLocation;
zoomLocation.latitude = 41.869271;
zoomLocation.longitude= -87.666436;
// 2
MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation, 0.85*METERS_PER_MILE, 0.85*METERS_PER_MILE);
// 3
MKCoordinateRegion adjustedRegion = [__mapView regionThatFits:viewRegion];
// 4
[__mapView setRegion:adjustedRegion animated:YES];
CGRect frame = self.view.bounds;
frame.size.height = frame.size.height - 40;
// Do any additional setup after loading the view, typically from a nib.
[self initRoutes];
timer = [NSTimer scheduledTimerWithTimeInterval: 5 target:self selector:#selector(updateLocations) userInfo:nil repeats: YES];
}
- (void)viewWillAppear:(BOOL)animated {
}
- (void)updateLocations {
[self updateBuses];
[self._mapView removeAnnotations:_Anns];
_Anns = [[NSMutableArray alloc] init];
for (int i = 0; i < _Buses.count; i++){
UICBus_Bus *Temp = _Buses[i];
CLLocationCoordinate2D ctrpoint;
ctrpoint.latitude = [Temp.getLat floatValue];
ctrpoint.longitude = [Temp.getLon floatValue];
MKAnnotation *addAnnotation = [[MKAnnotation alloc] initWithTitle:Temp.getMac andCoordinate:ctrpoint];
[_Anns addObject:addAnnotation];
}
[self._mapView addAnnotations:_Anns];
}
// ********************** Still need to add code to determine if bus is active or not **********************
- (void)updateBuses {
NSURL *url = [NSURL URLWithString:#"http://bus.uic.edu/api/latest"];
NSData *content = [NSData dataWithContentsOfURL:url];
NSError *JSONe;
_BusesInput = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:&JSONe];
_Buses = [[NSMutableArray alloc] init];
UICBus_Bus *Temp;
if(_BusesInput.count < 1){
NSLog(#"No Buses Found/Empty JSON");
}else{
for (NSString* key in _BusesInput){
Temp = [[UICBus_Bus alloc] init:[_BusesInput objectForKey:key]];
[_Buses addObject:Temp];
}
}
}
- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views{
MKAnnotationView *annotationView = [views objectAtIndex:0];
id <MKAnnotation> mp = [annotationView annotation];
[mv selectAnnotation:mp animated:YES];
}
- (void)viewDidUnload {
[self set_mapView:nil];
[super viewDidUnload];
}
#end
So, can I get this code to display a custom pin or do I need to rework it? and how?
You can directly work with didAddAnnotationViews method and didSelectAnnotation possibly while displaying and selecting custom image resp.
I found this link to help you best with How do I add custom pins to the iPhone MapKit?
Hope this helps.

Tracking user location all the time algorithm for an iphone app

I'm developing an iphone app that tracks the user location all the time.
The location can be in accuracy of handerts of meters (up to 400-500). And should be updated at least once an hour (even if there is no change in user's location, I would like to keep track on it)
I would like to know what is the best way to do that.
If I use CLLocation, I would like to use startupdatinglocation once in an hour and then use startmonitoringsignificantlocationchanges. Do you think it's the best way to do that causing minimum battery drain
The other option is using a geolocation api like geoloqi but i assume that using the realtime tracking mode all the time would cause a battery drain and the passive mode is not good enough accuracy (as i understood it gives accuracy like in wich city are you)
I would be glad if someone has any idea for a recommended api i could use or an efficient algorithm to use CLLocation to solve my problem.
Thank you!
You can track the location by maintaining a variable which reads the location from the GPS software and write the algorithm using a timer that reads the location every second or whatever precision u want
Try this code I think This will be work for you.
In .h file add this code
#import "CoreLocation/CoreLocation.h"
#import "MapKit/MapKit.h"
#interface AddressAnnotation : NSObject<MKAnnotation>
{
CLLocationCoordinate2D coordinate;
NSString *mTitle;
NSString *mSubTitle;
}
#end
#interface NearestPropertyMatchViewController : UIViewController<MKMapViewDelegate> {
CLLocationManager *locationManager;
IBOutlet MKMapView *searchMap;
NSMutableArray *searchListArray;
AddressAnnotation *addAnnotation;
}
-(CLLocationCoordinate2D) addressLocation:(NSString *)str;
#property (nonatomic, retain) CLLocationManager *locationManager;
#end
In .m file add this code.
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[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);
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=100;
span.longitudeDelta=100;
region.span=span;
for(int i=0;i<[regestrationArray count];i++)
{
CLLocationCoordinate2D location = [self addressLocation:[regestrationArray objectAtIndex:i]];
region.center=location;
addAnnotation = [[AddressAnnotation alloc] initWithCoordinate:location];
[searchMap addAnnotation:addAnnotation];
[searchMap setRegion:region animated:TRUE];
[searchMap regionThatFits:region];
}
-(CLLocationCoordinate2D) addressLocation :(NSString *)str
{
NSError* error = nil;
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
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 {
//Show error
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;
NSLog(#" lati=%f lon=%f",latitude,longitude);
return location;
}
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation
{
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentloc"];
annView.pinColor = MKPinAnnotationColorGreen;
annView.animatesDrop=TRUE;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}

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.

I am not able to give an MKAnnotation an image!

Hey guys! I am having some trouble with giving an MKAnnotationView an image instead of a pin view. In other words, I am having trouble displaying a target image (target.png) instead of the normal pin view. Here is my code---
// .h file
#import //Here it says to import mapkit & UIKit. The code blockquote doesn't let me
#import //show you that
#interface AddressAnnotation : NSObject {
CLLocationCoordinate2D coordinate;
NSString *mTitle;
NSString *mSubTitle;
}
#end
#interface ChosenLocationMap : UIViewController {
IBOutlet MKMapView *mapView;
AddressAnnotation *addAnnotation;
}
-(CLLocationCoordinate2D) addressLocation;
// .m file
#implementation AddressAnnotation
#synthesize coordinate;
- (NSString *)subtitle{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *stitle = [prefs objectForKey:#"addressKey"];
return #"%#",stitle;
}
- (NSString *)title{
return #"TARGET";
}
-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
coordinate=c;
NSLog(#"%f,%f",c.latitude,c.longitude);
return self;
}
#end
#implementation ChosenLocationMap
#synthesize destinationLabel, startbutton, accelloop, aimview, bombblowupview, bombleftview1, bombleftview2, bombleftview3, firebutton;
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
- (void)viewDidLoad {
mapView.mapType = MKMapTypeSatellite;
MKCoordinateSpan span;
span.latitudeDelta=0.2;
span.longitudeDelta=0.2;
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];
[super viewDidLoad];
}
-(CLLocationCoordinate2D) addressLocation {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *destinationstring = [prefs objectForKey:#"addressKey"];
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[destinationstring 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 {
//Show error
}
CLLocationCoordinate2D location;
location.latitude = latitude;
location.longitude = longitude;
return location;
}
- (MKAnnotationView *)map:(MKMapView *)map viewForAnnotation:(id )annotation{
MKAnnotationView *annView;
annView = (MKAnnotationView *) [mapView dequeueReusableAnnotationViewWithIdentifier:annotation.title];
if(annView == nil)
annView = [[[MKAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:annotation.title] autorelease];
else
annView.annotation = annotation;
[annView setImage:[UIImage imageNamed:#"target.png"]];
annView.canShowCallout = TRUE;
return annView;
}
Please note that I only included the code that actually involves the mapview. Thanks in advance!
EDIT: I Changed the code in my Xcode document for the changes in answer 1. I am too lazy to transfer everything to the code block above, and still, the picture still doesn't work.
SHOOP DA EDIT: Thank you for replying! My solution was that I forgot to say mapView.delegate = self. Bye!
Wow so much wrong with this code :-)
First you are missing a #property declaration in your AddressAnnotation
#property (nonatomic,assign) CLLocationCoordinate2D coordinate;
In the subtitle method you do this:
return #"%#",stitle;
But this is Objective-C and not Python, so you might want to change this to:
return stitle;
Then your initWithCoordinate is completely wrong. You do not initialize super. This is better:
-(id) initWithCoordinate: (CLLocationCoordinate2D) c
{
if ((self = [super init]) != nil) {
coordinate=c;
NSLog(#"%f,%f",c.latitude,c.longitude);
}
return self;
}
Try fixing that stuff first to see if it helps :-)
I'm new to Objective C but I think the prototype for your delegate function should be :
- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id )annotation{
MKAnnotationView *annView;
The delegate name is mapView:viewForAnnotation:, not map:viewForAnnotation:
Also you AddressAnnotation doesn't implement the MKAnnotation protocol