MapKit always centers on userlocation - ios

I have a map that zooms appropriately to the current location on load, but then doesn't allow you to pan around the map without it immediately zooming back in on the user location. I have been playing around with tracking mode but haven't gotten the right fix.. Here is some code, I appreciate the help.
- (void)viewDidLoad
{
[super viewDidLoad];
contentArray = [[NSMutableArray alloc] init];
mapViewuno.delegate = self;
mapViewuno.mapType = MKMapTypeStandard;
mapViewuno.userInteractionEnabled=YES;
locationManager = [[CLLocationManager alloc] init];
// Do any additional setup after loading the view, typically from a nib.
}
- (BOOL)prefersStatusBarHidden {
return YES;
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.navigationController.navigationBarHidden = YES;
indexValue = 0;
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"mapAddress" ofType:#"plist"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
NSString *strID = [NSString stringWithFormat:#"%d",intID];
NSLog(#"array : %#",[dict objectForKey:strID]);
[contentArray removeAllObjects];
[contentArray addObjectsFromArray:[dict objectForKey:strID]];
[contentArray retain];
[self zoomToUserLocation:mapViewuno.userLocation];
}
- (void)zoomToUserLocation:(MKUserLocation *)userLocation
{
if (!userLocation)
return;
MKCoordinateRegion region;
region.center = userLocation.location.coordinate;
region.span = MKCoordinateSpanMake(.5, .5);
region = [mapViewuno regionThatFits:region];
[mapViewuno setRegion:region animated:YES];
counter = 0;
[mapViewuno removeAnnotations:mapViewuno.annotations];
if([contentArray count] != 0)
{
for(indexValue = 0; indexValue<[contentArray count];indexValue++)
{
FirstAnnotation *obj=[[FirstAnnotation alloc]init];
obj.latitude = [[[contentArray objectAtIndex:indexValue] objectForKey:#"lattitude"] floatValue];
obj.longitude = [[[contentArray objectAtIndex:indexValue] objectForKey:#"Longitude"] floatValue];
obj.titleName=[[contentArray objectAtIndex:indexValue] objectForKey:#"Title"];
obj.Address = [[contentArray objectAtIndex:indexValue] objectForKey:#"Address"];
obj.Phone = [[contentArray objectAtIndex:indexValue] objectForKey:#"Phone"];
obj.intTag = indexValue;
[mapViewuno addAnnotation:obj];
}
if ([mapViewuno.annotations count] == 0) return;
// [self.mapView setRegion:newRegion animated:YES];
}
}
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
[self zoomToUserLocation:userLocation];
}

This part is causing the problem:
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
[self zoomToUserLocation:userLocation];
}
Every time the mapview's location manager gets a new fix (i.e. every second or so) the mapview calls that delegate method which in turn calls your method to zoom. Put in a BOOL like zoomedToUserLocation and set it to NO at init time, then to YES when it hits zoomToUserLocation the first time.

Related

exception 'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'

usually this code has worked perfectly for me, up until recently I went to update my project to support the latest iOS and when clicking on the map button, receive the error;
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'
Prior to using Xcode 9 it would work correctly, so I am guessing the way the code works is slightly different now.
The array is NSArray *arr_OfCountryCode;
And we initialise it in the viewDidLoad
//Initialize NSArray object with Images
arr_OfCountryCode=#[#"AF",#"AL",#"DZ",#"AS",#"AD",#"AO",#"AI",#"AQ",#"AG",#"AR",#"AM",#"AW",#"AC",#"AU",#"AT",#"AZ",#"BS",#"BH",#"BD",#"BB",#"BY",#"BE",#"BZ",#"BJ",#"BM",#"BT",#"BO",#"BA",#"BW",#"BV",#"BR",#"IO",#"VG",#"BN",#"BG",#"BF",#"BI",#"KH",#"CM",#"CA",#"IC",#",CV",#"BQ",#"KY",#"CF",#"EA",#"TD",#"CL",#"CN",#"CX",#"CP",#"CC",#"CO",#"KM",#"CD",#"CG",#"CK",#"CR",#"HR",#"CU",#"CW",#"CY",#"CZ",#"CI",#"DK",#"DG",#"DJ",#"DM",#"DO",#"EC",#"EG",#"SV",#"GQ",#"ER",#"EE",#"ET",#"FK",#"FO",#"FJ",#"FI",#"FR",#"FG",#"PF",#"TF",#"GA",#"GM",#"GE",#"DE",#"GH",#"GI",#"GR",#"GL",#"GD",#"GP",#"GU",#"GT",#"GG",#"GN",#"GW",#"GY",#"HT",#"HM",#"HN",#"HK",#"HU",#"IS",#"IN",#"ID",#"IR",#"IQ",#"IE",#"IM",#"IL",#"IT",#"JM",#"JP",#"JE",#"JO",#"KZ",#"KE",#"KI",#"XK",#"KW",#"KG",#"LA",#"LV",#"LB",#"LS",#"LR",#"LY",#"LI",#"LT",#"LU",#"MO",#"MK",#"MG",#"MW",#"MY",#"MV",#"ML",#"MT",#"MH",#"MQ",#"MR",#"MU",#"YT",#"MX",#"FM",#"MD",#"MC",#"MN",#"ME",#"MS",#"MA",#"MZ",#"MM",#"NA",#"NR",#"NP",#"NL",#"NC",#"NZ",#"NI",#"NE",#"NG",#"NU",#"NF",#"KP",#"MP",#"NO",#"OM",#"PK",#"PW",#"PS",#"PA",#"PG",#"PY",#"PE",#"PH",#"PN",#"PL",#"PT",#"PR",#"QA",#"RO",#"RU",#"RW",#"RE",#"WS",#"SM",#"SA",#"SN",#"RS",#"SC",#"SL",#"SG",#"SX",#"SK",#"SI",#"SB",#"SO",#"ZA",#"GS",#"KR",#"SS",#"ES",#"LK",#"BL",#"SH",#"KN",#"LC",#"MF",#"PM",#"VC",#"SD",#"SR",#"SJ",#"SZ",#"SE",#"CH",#"SY",#"ST",#"TW",#"TJ",#"TZ",#"TH",#"TL",#"TG",#"TK",#"TO",#"TT",#"TA",#"TN",#"TR",#"TM",#"TC",#"TV",#"UM",#"VI",#"UG",#"UA",#"AE",#"GB",#"US",#"UY",#"UZ",#"VU",#"VA",#"VE",#"VN",#"WF",#"EH",#"YE",#"ZM",#"ZW",#"AX"];
When the user taps the button, a location on the map is shown at random, within the actionMethod to do that is;
str_Type = #"Randum";
self.mapView.hidden = NO;
int randomIndex = arc4random() % [arr_OfCountryCode count];
NSString *urlString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=false",[arr_OfCountryCode objectAtIndex:randomIndex]];
NSURL *url = [[NSURL alloc] initWithString:urlString];
I am struggling as to why the array is classed as empty when it worked for multiple iOS versions and devices prior to the latest.
It is showing as nil as soon as I check it in Xcode, other arrays initialise before it with no issue, I even tried copying an existing array, renaming it to *arr_OfCountryCode; and that still showed as nil !
In this method (entire posted below) I believe the problem is occuring.
- (IBAction)actionMethod:(UIButton *)sender {
if ([sender tag] == 0) {
self.musicView.hidden = NO;
[self.tbl_MusicTable reloadData];
} else if ([sender tag] == 1) {
str_Type = #"Randum";
self.mapView.hidden = NO;
int randomIndex = arc4random() % [arr_OfCountryCode count];
NSString *urlString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=false",[arr_OfCountryCode objectAtIndex:randomIndex]];
NSURL *url = [[NSURL alloc] initWithString:urlString];
[NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:url] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"%#",error.description);
} else {
NSDictionary *jsonObject=[NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableLeaves
error:nil];
NSDictionary *places = [[[[jsonObject objectForKey:#"results"] objectAtIndex:0] objectForKey:#"geometry"] objectForKey:#"location"];
NSDictionary *locations = [[[jsonObject objectForKey:#"results"] objectAtIndex:0] objectForKey:#"address_components"];
float lat = [[places objectForKey:#"lat"] floatValue];
float lon = [[places objectForKey:#"lng"] floatValue];
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.50;
span.longitudeDelta = 0.50;
location.latitude = lat;
location.longitude = lon;
region.span = span;
region.center = location;
[self.mk_MapView setRegion:region animated:YES];
NSString *str_Title = [[locations valueForKey:#"long_name"] objectAtIndex:0];
NSString *str_Short = [[locations valueForKey:#"short_name"] objectAtIndex:0];
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = location;
point.title = str_Title;
point.subtitle = str_Short;
[self.mk_MapView addAnnotation:point];
}
}];
}
}
The further code for corelocation is here
#pragma mark - CLLocationManager Delegate Method
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if ([str_Type isEqualToString:#"Custom"]) {
CLLocation *currentLocation = newLocation;
NSString *str_Longitude;
NSString *str_Latitude;
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.020;
span.longitudeDelta = 0.020;
location.latitude = currentLocation.coordinate.latitude;
location.longitude = currentLocation.coordinate.longitude;
region.span = span;
region.center = location;
[self.mk_MapView setRegion:region animated:YES];
if (currentLocation != nil) {
str_Longitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
str_Latitude = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
}
// Reverse Geocoding
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = currentLocation.coordinate;
point.title = placemark.country;
point.subtitle = placemark.locality;
[self.mk_MapView addAnnotation:point];
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
} else {
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = location;
point.title = placemark.country;
point.subtitle = placemark.locality;
[self.mk_MapView addAnnotation:point];
}
}
#pragma mark - MKMapView Delegate Methods
-(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation
{
MKAnnotationView *pinView = nil;
if(annotation != self.mk_MapView.userLocation)
{
static NSString *defaultPinID = #"com.invasivecode.pin";
pinView = (MKAnnotationView *)[self.mk_MapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( pinView == nil )
pinView = [[MKAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:defaultPinID];
//pinView.pinColor = MKPinAnnotationColorGreen;
pinView.canShowCallout = YES;
//pinView.animatesDrop = YES;
pinView.image = [UIImage imageNamed:#"HesOnThisMap"]; //
}
else {
//[self.mk_MapView.userLocation setTitle:#"I am here"];
}
return pinView;
}
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
MKAnnotationView *aV;
for (aV in views) {
CGRect endFrame = aV.frame;
aV.frame = CGRectMake(aV.frame.origin.x, aV.frame.origin.y - 230.0, aV.frame.size.width, aV.frame.size.height);
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.45];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[aV setFrame:endFrame];
[UIView commitAnimations];
}
}
It was to do with the google maps api callbacks, it was crashing when it hit the maximum callbacks

MapBox polyline not shown on map

I have a problem when trying to add a polyline on the map.
I get directions from MKDirections, and create a RMPolylineAnnotation, but it does not appear on the map.
As I can see, the following method is called just once when the map appears:
- (RMMapLayer *)mapView:(RMMapView *)mapView layerForAnnotation:(RMAnnotation *)annotation
Here is the code I am using:
- (void)getRoute {
CLLocation *source = [[CLLocation alloc] initWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude];
CLLocation *destination = [[CLLocation alloc] initWithLatitude:self.mapView.selectedAnnotation.coordinate.latitude longitude:self.mapView.selectedAnnotation.coordinate.longitude];
[AppleDirectionManager getDirectionsFromPoint:source toPoint:destination transportType:MKDirectionsTransportTypeAutomobile withCompletion:^(MKDirectionsResponse *result) {
self.routeStepsArray = [[result.routes firstObject] steps];
for (MKRoute *route in result.routes) {
NSMutableArray *points = [NSMutableArray array];
for (int i = 0; i < route.polyline.pointCount; i++) {
MKMapPoint point = route.polyline.points[i];
CLLocation *location = [[CLLocation alloc] initWithLatitude:point.x longitude:point.y];
[points addObject:location];
}
dispatch_async(dispatch_get_main_queue(), ^{
NSArray *arr = [points copy];
RMPolylineAnnotation *polyline = [[RMPolylineAnnotation alloc] initWithMapView:self.mapView points:arr];
[self.mapView addAnnotation:polyline];
});
}
}];
}
- (RMMapLayer *)mapView:(RMMapView *)mapView layerForAnnotation:(RMAnnotation *)annotation {
if (annotation.isUserLocationAnnotation)
return nil;
RMMarker *marker = [[RMMarker alloc] initWithUIImage:[UIImage imageNamed:#"blabla.png"]];
[marker setCanShowCallout:YES];
[marker setName:#"blabla"];
return marker;
}
Also I can not show a custom callout for a RMPointAnnotation.
For RMPointAnnotation it's easily.
_polylineAnnotation = [[RMPolylineAnnotation alloc] initWithMapView:_mapView points:#[Location,Location]];
_polylineAnnotation.lineColor = [UIColor redColor];
_polylineAnnotation.lineWidth = 10.0f;
[_mapView addAnnotation:_polylineAnnotation];

Map Annotations Displayed on Date

I have a map that displays an array of annotations. These annotations are all called from a plist and each have a date at which they occur. I would like these annotations to display only on the date that they happen, however I have no clue how to approach this. Any help would be much appreciated.
for (NSString *dateString in contentArray) {
[[NSUserDefaults standardUserDefaults] stringForKey:#"Date"];
}
This is the little bit of code I have written in but it does not solve anything for me.
EDIT:
Here is the code that calls the annotations generally.
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.navigationController.navigationBarHidden = YES;
indexValue = 0;
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"mapAddress" ofType:#"plist"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
NSString *strID = [NSString stringWithFormat:#"%d",intID];
NSLog(#"array : %#",[dict objectForKey:strID]);
[contentArray removeAllObjects];
[contentArray addObjectsFromArray:[dict objectForKey:strID]];
[contentArray retain];
[self zoomToUserLocation:mapViewuno.userLocation];
}
- (void)zoomToUserLocation:(MKUserLocation *)userLocation
{
if (!userLocation)
return;
MKCoordinateRegion region;
region.center = userLocation.location.coordinate;
region.span = MKCoordinateSpanMake(.5, .5);
region = [mapViewuno regionThatFits:region];
[mapViewuno setRegion:region animated:YES];
counter = 0;
[mapViewuno removeAnnotations:mapViewuno.annotations];
if([contentArray count] != 0)
{
for(indexValue = 0; indexValue<[contentArray count];indexValue++)
{
FirstAnnotation *obj=[[FirstAnnotation alloc]init];
obj.latitude = [[[contentArray objectAtIndex:indexValue] objectForKey:#"lattitude"] floatValue];
obj.longitude = [[[contentArray objectAtIndex:indexValue] objectForKey:#"Longitude"] floatValue];
obj.titleName=[[contentArray objectAtIndex:indexValue] objectForKey:#"Title"];
obj.Address = [[contentArray objectAtIndex:indexValue] objectForKey:#"Address"];
obj.Phone = [[contentArray objectAtIndex:indexValue] objectForKey:#"Phone"];
obj.intTag = indexValue;
[mapViewuno addAnnotation:obj];
}
if ([mapViewuno.annotations count] == 0) return;
// [self.mapView setRegion:newRegion animated:YES];
}
}

Plot two different color of mapview pin

I'm trying to display mapview with an array of coordinates. So, i load the latitudes and longitudes from array where those are contains. It is showing perfectly. Now, i want to display one paritcular latitude & longitude with different color pin. I've referred this answer no such different i can't see.
ViewController.m
-(void)showMap:
{
...
...
DataProvider *d = [DataProvider getInstance];
NSInteger numb = sender.view.tag;
d.colorlatitude = [[arraxy objectAtIndex:numb] objectForKey:#"lat"];
d.colorlongitude = [[arraxy objectAtIndex:numb] objectForKey:#"lng"];
[d._address removeAllObjects];
[arraxy removeObjectAtIndex:sender.view.tag];
d._address = arraxy;
MapViewController *map = [[MapViewController alloc]initWithNibName:#"MapViewController" bundle:nil];
[self.navigationController pushViewController:map animated:YES];
}
MapViewController.m
-(void)viewWillAppear:(BOOL)animated
{
DataProvider *d = [DataProvider getInstance];
[_mapView removeAnnotations:_mapView.annotations];
RegisterViewController *appDelegate = [[RegisterViewController alloc]init];
[_mapView setShowsUserLocation:YES];
[_mapView setRegion:MKCoordinateRegionMakeWithDistance([appDelegate.locationManager location].coordinate, 1000, 1000)];
[_mapView setUserTrackingMode:MKUserTrackingModeNone];
MKCoordinateRegion rregion = {{0.0,0.0},{0.0,0.0}};
rregion.center.latitude = [d.colorlatitude floatValue];
rregion.center.longitude = [d.colorlongitude floatValue];
rregion.span.latitudeDelta=0.001f;
rregion.span.longitudeDelta=0.001f;
[_mapView setRegion:rregion];
MapviewAnnotations *add = [[MapviewAnnotations alloc]init];
add.coordinate = rregion.center;
[_mapView addAnnotation:add];
if (d._address)
{
for (int i=0; i<[d._address count]; i++)
{
NSDictionary *dic=[d._address objectAtIndex:i];
MKCoordinateRegion region={{0.0,0.0},{0.0,0.0}};
region.center.latitude=[[dic objectForKey:#"lat"]floatValue];
region.center.longitude=[[dic objectForKey:#"lng"]floatValue];
region.span.latitudeDelta=0.001f;
region.span.longitudeDelta=0.001f;
[_mapView setRegion:region];
MapviewAnnotations *ann=[[MapviewAnnotations alloc]init];
ann.coordinate=region.center;
[_mapView addAnnotation:ann];
}
}
[super viewWillAppear:YES];
}
and my MKMapView's delegate method is
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if (![annotation isKindOfClass:[MapviewAnnotations class]])
{
return nil;
}
static NSString *reuseId = #"currentloc";
MKPinAnnotationView *annView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
if (annView == nil)
{
annView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId];
annView.animatesDrop = NO;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
}
else
{
annView.annotation = annotation;
}
DataProvider *mvAnn = [DataProvider getInstance];
if (mvAnn.colorlatitude) // here i'm checking the condition.
{
annView.pinColor = MKPinAnnotationColorGreen;
}
else
{
annView.pinColor = MKPinAnnotationColorRed;
}
return annView;
}
I'm just writting the condition if the co-ordinate is there i've to plot the green color pin to that particular coordinate only. How to achieve this?
The difference between your code and the one Hinata has referred you to is that the if statement in the other code uses a value (yesno) on the annotation it is currently drawing to decide what colour to use. You are getting a value from DataProvider but not telling it which annotation you are drawing, so the instance it gives you is just what ever the instance method feels like returning at the time the map is asking for the pin. You need to tell it what you're drawing for it to decide what to put into colorlatitude
I've done this through some flags like below inside of my - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
MapviewAnnotations *mvAnn = (MapviewAnnotations *)annotation;
if (mvAnn.flag == 1)
{
annView.pinColor = MKPinAnnotationColorGreen;
}
else if (mvAnn.flag == 10)
{
annView.pinColor = MKPinAnnotationColorPurple;
}
else
{
annView.pinColor = MKPinAnnotationColorRed;
}
In my viewWillAppear i received the coordinates from DataProvider and assigned with separate MapviewAnnotations with flags and differentiate it with three type of pins simply.
Cheers!

Objective-C: How can I pass string to a .xib file and display a MapView?

I have a .xib file where the user can enter a location name of a place in a UITextField and click search. Then another .xib file will load where the user will see a MapView object with the location on the map.
I made a custom init method where I pass the string as follows when the user clicks the button:
AddLocViewController *locView = [[AddLocViewController alloc] initWithNibName:nil bundle:nil customLoc:textLoc.text];
[self presentModalViewController:locView animated:YES];
In the new ViewController class called AddLocViewController.m the init method and viewDidLoad is as following:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil customLoc:(NSString*)_loc
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
stringLoc1 = _loc;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self showAddress];
}
Here [self showAddress] calls a method to display the contents on the mapView object, The showAddress method works perfectly if I have a UITextField taking input and clicking a button to set the value to a NSString object stringLoc and using that in showAddress method:
- (void) showAddress
{
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta=0.01f;
span.longitudeDelta=0.01f;
stringLoc1 = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[addressField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:stringLoc1]];
NSArray *listItems = [locationString componentsSeparatedByString:#","];
double aLatitude = 0.0;
double aLongitude = 0.0;
if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:#"200"]) {
aLatitude = [[listItems objectAtIndex:2] doubleValue];
aLongitude = [[listItems objectAtIndex:3] doubleValue];
}
else {
[addressField setText: #"Address Location error"];
return;
}
[addressField resignFirstResponder];
CLLocationCoordinate2D location = {latitude: aLatitude, longitude:aLongitude};
region.span=span;
region.center.latitude = aLatitude;
region.center.longitude = aLongitude;
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];
}
Please help me pass parameter here to this class and use the showAddress method appropriately because it only now shows the proper location when a location is searched from within the class and does not show the proper location when instantiated.
Here you overwrite stringLoc1 with the content of the address field:
It is overwritten regardless of its initial value. If the textField is empty then it is overwirtten with an empty string.
stringLoc1 = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[addressField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
I am not sure what the best solution is in the context of your remaining code. But this should work:
NSString *currentLoc;
if (addressField.text && ([addressField.text length] == 0)) {
currentLoc = addressFiled.text;
stringLoc1 = addressField.text; // this line will set the current value as default value for the next call of the method; unless a new init call comes in between.
}
else
currentLoc = stringLoc1;
currentLoc = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",
[currentLoc stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:currentLoc ]];
I am sure there are smarter ways of doing that. But this should work with minimal changes to the view lines of code that you shared with us.

Resources