MapKit/CoreLocation iOS7 why can't I save annotation data (coordinates) to array? - ios7

Alright, I've looked high and low for an answer to this. Why can I query the mapview.annotations array for coordinate data but I cant save the same annotation data at generation into an array that is query-able in the same fashion.
This is my code:
- (void)retrieveData {
NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:#"http://PRIVATE.com/api/cprapi.php?function=request&uid=PRIVATE"]];
NSLog(#"%#",url);
NSData * data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
workzoneArray = [[NSMutableArray alloc]init];
for (int i = 0; i < json.count; i++) {
//Create workzone objects
NSString * sT = [[json objectAtIndex:i]objectForKey:#"startTime"];
NSString * eT = [[json objectAtIndex:i]objectForKey:#"endTime"];
NSString * sLat = [[json objectAtIndex:i]objectForKey:#"startLat"];
NSString * sLon = [[json objectAtIndex:i]objectForKey:#"startLon"];
NSString * eLat = [[json objectAtIndex:i]objectForKey:#"endLat"];
NSString * eLon = [[json objectAtIndex:i]objectForKey:#"endLon"];
NSString * A = [[json objectAtIndex:i]objectForKey:#"active"];
NSString * DUID = [[json objectAtIndex:i]objectForKey:#"deviceUID"];
LTB * workzone = [[LTB alloc] initWithStartTime:sT andEndTime:eT andStartLat:sLat andStartLon:sLon andEndLat:eLat andEndLon:eLon andActive:A andDeviceUID:DUID];
[workzoneArray addObject:workzone];
NSLog(#"workzoneArray: %#", workzoneArray);
}
for (int i = 0; i < workzoneArray.count; i++) {
LTB * workzone = [workzoneArray objectAtIndex:i];
CLLocationCoordinate2D thiscoordinate;
CLLocationCoordinate2D thatcoordinate;
float sLat = [workzone.startLat floatValue];
float sLon = [workzone.startLon floatValue];
NSLog(#"Start: %# %#",workzone.startLat,workzone.startLon);
float eLat = [workzone.endLat floatValue];
float eLon = [workzone.endLon floatValue];
NSLog(#"End: %# %#",workzone.endLat,workzone.endLon);
thiscoordinate.latitude = sLat;
thiscoordinate.longitude = sLon;
thatcoordinate.latitude = eLat;
thatcoordinate.longitude = eLon;
myAnnotation *annotation1 = [[myAnnotation alloc] initWithCoordinate:thiscoordinate title:#"Limit"];
[self.mapView addAnnotation:annotation1];
[AnnotationArray addObject:annotation1];
myAnnotation * annotation2 = [[myAnnotation alloc] initWithCoordinate:thatcoordinate title:#"Limit"];
[self.mapView addAnnotation:annotation2];
[AnnotationArray addObject:annotation2];
NSLog(#"%#", AnnotationArray);
NSLog(#"%#", [AnnotationArray objectAtIndex:0]);
NSLog(#"%#", [AnnotationArray objectAtIndex:1]);
}
}
and the code that handles comparisons between my points where I am attempting to pull data from my array.
-(void) mapView:(MKMapView *)mapView
didUpdateUserLocation:(MKUserLocation *)userLocation
{
NSLog(#"checking distances...");
myAnnotation * annotation = [AnnotationArray objectAtIndex:0];
CLLocation *loc = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
NSLog(#"%f - %f", annotation.coordinate.latitude, annotation.coordinate.longitude);
annotation = [AnnotationArray objectAtIndex:1];
CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
NSLog(#"%f - %f", annotation.coordinate.latitude, annotation.coordinate.longitude);
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude];
CLLocationDistance dist = [loc1 distanceFromLocation:loc2];
float distance = dist;
NSLog(#"%f", distance);
if (distance < 50) {
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Limit Alert"
message:#"50 Meters to Limit"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[message show];
}
}
If I objectAtIndex the self.mapView.annotations I get the correct lat and lon, so I'm guessing it's an invalid type conversion as it goes into the array am I right in thinking that?
Is there a better way I could do that? I only am looking at using the array as the mapView.annotations is unreliable based on network speed to which annotated view is at which index with out alot more code.
The goal is to compare loc1 and loc2 get the distance between them. compare current location's distance to loc1 add the current location's distance to loc2 and if within a margin of error check that it is less or the same. But I cant do this until I figure out a reliable way of knowing which mapView.annotation is which.
Maybe I'm blind. Thanks!
ANSWER:
Looked through my code again, decided to use my earlier array which I fed my JSON into and then extract data from there as that will allow it to be extended further down the road. Here's the code I wound up with and it seems to work ok.
NSLog(#"checking distances...");
LTB * workzone = [workzoneArray objectAtIndex:0];
CLLocationCoordinate2D startCoord;
CLLocationCoordinate2D endCoord;
double sLat = [workzone.startLat doubleValue];
double sLon = [workzone.startLon doubleValue];
startCoord.latitude = sLat;
startCoord.longitude = sLon;
double eLat = [workzone.endLat doubleValue];
double eLon = [workzone.endLon doubleValue];
endCoord.latitude =eLat;
endCoord.longitude = eLon;
CLLocation *loc = [[CLLocation alloc] initWithLatitude:startCoord.latitude longitude:startCoord.longitude];
NSLog(#"%f - %f", startCoord.latitude, startCoord.longitude);
CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:endCoord.latitude longitude:endCoord.longitude];
NSLog(#"%f - %f",endCoord.latitude, endCoord.longitude);
CLLocation *myloc = [[CLLocation alloc] initWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude];
CLLocationDistance area = [loc distanceFromLocation:loc1];
NSLog(#"area: %f",area);
CLLocationDistance distToA = [myloc distanceFromLocation:loc];
NSLog(#"distToA %f",distToA);
CLLocationDistance distToB = [myloc distanceFromLocation:loc1];
NSLog(#"distToB %f",distToB);
double outOfBounds = ((distToA+distToB) - area);
NSLog(#"%f", outOfBounds);
if (outOfBounds < (area + 50)) {
if (workzoneAlert == TRUE) {
workzoneAlert = false;
}
if (distToA < 10) {
if (workzoneAlertA == false) {
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Limit Alert"
message:#"10 Meters to Limit A"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[message show];
//set variable so it only shows once
self.workzoneAlertA = true;
}
else {
}
}
else if (distToB <10) {
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Limit Alert"
message:#"10 Meters to Limit B"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[message show];
}
}
else {
if (workzoneAlert == FALSE){
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Limit Alert"
message:#"Exceeded WorkZone"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[message show];
workzoneAlert = TRUE;
}
}
}

Related

How can I display Latitude & Longitude in 19.0176° N, 72.8562° E format in Objective c

I am using the following code to get the current location,I have added the Corelocation framework
- (void)viewDidLoad {
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
NSInteger degrees = newLocation.coordinate.latitude;
double decimal = fabs(newLocation.coordinate.latitude - degrees);
int minutes = decimal * 60;
double seconds = decimal * 3600 - minutes * 60;
NSString *lattitudeStr = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
degrees, minutes, seconds];
_latitudeLabel.text = lattitudeStr;
degrees = newLocation.coordinate.longitude;
decimal = fabs(newLocation.coordinate.longitude - degrees);
minutes = decimal * 60;
seconds = decimal * 3600 - minutes * 60;
NSString *longitudeStr = [NSString stringWithFormat:#"%d° %d' %1.4f\"",
degrees, minutes, seconds];
_longitudeLabel.text = longitudeStr;
}
// Stop Location Manager
[locationManager stopUpdatingLocation];
NSLog(#"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^
(NSArray *placemarks, NSError *error)
{
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0)
{
placemark = [placemarks lastObject];
_addressLabel.text = [NSString stringWithFormat:#"%#\n%# %#\n%#\n%#",
placemark.thoroughfare,
placemark.postalCode, placemark.locality,
placemark.administrativeArea,
placemark.country];
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
}
I am getting the values for,Latitude:19° 1’ 3.4129” and Longitude:72° 51’ 22.1918” So I need this coordinate display in 19.0176° N,72.8562° E format in Objective c. How to get the exact latitude and longitude. where i am doing the mistake or do i need to add any other method or function or framework or sample code.
You already have these values, see the comment this is what you want
if (currentLocation != nil) {
NSInteger degrees = newLocation.coordinate.latitude; //<--- this is what you want
NSString *lattitudeStr = [NSString stringWithFormat:#"%f° N",
degrees];
_latitudeLabel.text = lattitudeStr;
degrees = newLocation.coordinate.longitude; //<--- this is what you want
NSString *longitudeStr = [NSString stringWithFormat:#"%f° E",
degrees];
_longitudeLabel.text = longitudeStr;
}
NSString *lat = [self convertCoordinateFromDegreeMinuteSecond:#"19° 1’ 3.4129”" position:#"N"];
NSString *lon = [self convertCoordinateFromDegreeMinuteSecond:#"72° 51’ 22.1918”" position:#"E"];
- ( NSString * )convertCoordinateFromDegreeMinuteSecond:( NSString * )string position:( NSString * )position; {
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789."] invertedSet];
NSArray *arrayLat = [string componentsSeparatedByString:#" "];
if ( arrayLat.count == 3 ) {
NSString *degree = [[arrayLat[ 0 ] componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:#""];
NSString *minute = [[arrayLat[ 1 ] componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:#""];
NSString *second = [[arrayLat[ 2 ] componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:#""];
int sign = degree.doubleValue < 0 ? -1 : 1;
double coordinate = ( degree.doubleValue + ( sign * ( minute.doubleValue / 60. ) ) + ( sign * ( second.doubleValue / 3600. ) ) );
NSString *str = [NSString stringWithFormat:#"%f° %#", coordinate, position];
return str;
} else {
return #"NaN";
}
}

how to draw a path one place to another place in google map sdk iOS?

i need to find path in google map view one place to another place. how to draw a direction map using google map sdk iOS.
can any of give source code. and then explain how to achieve this.
Below i attached image also, i need to achieve this in iPhone app using Google Map SDK iOS.
Thanks,
-(void)showRoute:(id)routeDict {
NSString *pointStr = [[[[routeDict objectForKey:#"routes"] objectAtIndex:0] objectForKey:#"overview_polyline"] objectForKey:#"points"];
float max_long = 0.0;
float min_long = 0.0;
float max_lat = 0.0;
float min_lat = 0.0;
NSMutableArray *routeArr = [self decodePolyLine:pointStr];
CLLocationCoordinate2D commuterLotCoords[[routeArr count]];
CLLocation *loc;
if ([routeArr count]) {
loc = [routeArr objectAtIndex:0];
max_long = loc.coordinate.longitude;
min_long = loc.coordinate.longitude;
max_lat = loc.coordinate.latitude;
min_lat = loc.coordinate.latitude;
}
for (int i=0; i<[routeArr count]; i++) {
CLLocation *loc = [routeArr objectAtIndex:i];
commuterLotCoords[i] = loc.coordinate;
if (loc.coordinate.latitude > max_lat) {
max_lat = loc.coordinate.latitude;
}
if (loc.coordinate.latitude < min_lat) {
min_lat = loc.coordinate.latitude;
}
if (loc.coordinate.longitude > max_long) {
max_long = loc.coordinate.longitude;
}
if (loc.coordinate.longitude < min_long) {
min_long = loc.coordinate.longitude;
}
}
MKPolyline *overflowRoutePolygon = [MKPolyline polylineWithCoordinates:commuterLotCoords count:[routeArr count]];
[mapView addOverlay:overflowRoutePolygon];
//NSLog(#"%f %f %f %f",min_lat,max_lat,min_long,max_long);
if ( max_lat == 0.0 || min_lat == 0.0 || max_long == 0.0 || min_long == 0.0 ) {
} else {
//calculate center of map
float center_long = (max_long + min_long) / 2;
float center_lat = (max_lat + min_lat) / 2;
//calculate deltas
float deltaLat = max_lat - min_lat + .00032;
float deltaLong = max_long - min_long + .00032;
//NSLog(#"%f %f %f %f",center_lat,center_long,deltaLat,deltaLong);
//create new region and set map
CLLocationCoordinate2D cordinate;
cordinate.latitude = center_lat;
cordinate.longitude = center_long;
MKCoordinateSpan span = MKCoordinateSpanMake(deltaLat, deltaLong);
MKCoordinateRegion region = {cordinate, span};
[mapView setRegion:region];
}
}
-(void)showRoute
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
float sourceLat = 0.00;
float sourceLong = 0.00;
float destinationLat = 0.00;
float destinationLong = 0.00;
id record = [routeArray objectAtIndex:selectedIndex];
sourceLat = [[[[record objectForKey:#"To"] objectForKey:#"Latitude"] objectForKey:#"text"] floatValue];
sourceLong = [[[[record objectForKey:#"To"] objectForKey:#"Longitude"] objectForKey:#"text"] floatValue];
destinationLat = [[[[record objectForKey:#"From"] objectForKey:#"Latitude"] objectForKey:#"text"] floatValue];
destinationLong = [[[[record objectForKey:#"From"] objectForKey:#"Longitude"] objectForKey:#"text"] floatValue];
if ( sourceLat == 0.00 || sourceLong == 0.00 || destinationLat == 0.00 || destinationLong == 0.00 ) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Direction Error"
message: #"One of your destination is not valid."
delegate: self
cancelButtonTitle: #"OK"
otherButtonTitles: nil];
[alert show];
[alert release];
return;
}
NSString *urlStr = [NSString stringWithFormat: #"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=false",
sourceLat, sourceLong,
destinationLat,destinationLong];
NSLog(#"urlStr : %#",urlStr);
NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:urlStr]];
//NSLog(#"direction response : %#",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
JSONDecoder *jsonKitDecoder = [JSONDecoder decoder];
NSMutableDictionary *routeDic = [[jsonKitDecoder objectWithData:data] copy];
if ( ![[[routeDic objectForKey:#"status"] uppercaseString] isEqualToString:#"OK"] ) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Direction Error"
message: #"Not able to find direction from your default location."
delegate: self
cancelButtonTitle: #"OK"
otherButtonTitles: nil];
[alert show];
[alert release];
[pool release];
return;
}
[self performSelectorOnMainThread:#selector(showRoute:) withObject:routeDic waitUntilDone:YES];
[pool release];
return;
}
-(NSMutableArray *)decodePolyLine:(NSString *)encodedStr
{
NSMutableString *encoded = [[NSMutableString alloc] initWithCapacity:[encodedStr length]];
[encoded appendString:encodedStr];
[encoded replaceOccurrencesOfString:#"\\\\" withString:#"\\" options:NSLiteralSearch range:NSMakeRange(0, [encoded length])];
NSInteger len = [encoded length];
NSInteger index = 0;
NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
NSInteger lat = 0;
NSInteger lng = 0;
while (index < len) {
NSInteger b;
NSInteger shift = 0;
NSInteger result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
lng += dlng;
NSNumber *latitute = [[[NSNumber alloc] initWithFloat:lat * 1e-5] autorelease];
NSNumber *longitute = [[[NSNumber alloc] initWithFloat:lng * 1e-5] autorelease];
CLLocation *loc = [[[CLLocation alloc] initWithLatitude:[latitute floatValue] longitude:[longitute floatValue]] autorelease];
[array addObject:loc];
}
[encoded release];
return array;
}
pragma mark MKMapKitDelegate
- (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
HAnnotation *ann = (HAnnotation *)annotation;
static NSString *AnnotationViewID = #"annotationViewID";
HAnnotationView *annotationView = (HAnnotationView *)[map dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
if (annotationView == nil)
{
annotationView = [[[HAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID type:ann.type] autorelease];
}
annotationView.type = ann.type;
annotationView.annotation = annotation;
[annotationView setNeedsDisplay];
return annotationView;
}
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
MKAnnotationView *aV;
for (aV in views) {
MKAnnotationView* annotationView = aV;
annotationView.canShowCallout = NO;
}
}
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id < MKOverlay >)overlay
{
if( [overlay isKindOfClass:[MKPolyline class]] ) {
MKPolylineView *view = [[MKPolylineView alloc] initWithOverlay:overlay];
view.lineWidth=2;
view.strokeColor=[UIColor blueColor];
view.fillColor=[[UIColor blueColor] colorWithAlphaComponent:0.5];
return [view autorelease];
} else {
MKPolygonView *view = [[MKPolygonView alloc] initWithOverlay:overlay];
view.lineWidth=2;
view.strokeColor=[UIColor yellowColor];
view.fillColor=[[UIColor yellowColor] colorWithAlphaComponent:0.3];
return [view autorelease];
}
return nil;
}
Try this code i have used this code in my project it is working fine.
First of all pass source and destination latitude and longitude in the google api you will get all the points between that place and after parsing using poly line method you will draw line.simply use this methods make changes according to your variable and data .
i hope this will help you. This is from google api. Draw polyline and give paths lat long in it .
https://developers.google.com/maps/documentation/ios/shapes#customize_a_polyline

NSMutableArray sorting returning incorrect order

I am attempting to sort an NSMutableArray depending on the distance between two locations (the current location, and specified coordinates in the first for loop). However, the sort isn't returning any specific order, but instead a completely random order (see the pic here: http://u.maxk.me/iz7Z).
Please can you tell me where I am going wrong?
Sorting:
[self.venues sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [[obj1 objectForKey:#"distance"] compare:[obj2 objectForKey:#"distance"]];
}];
-setVenues:
- (void) setVenues:(NSMutableArray *)_venues {
if (venues != _venues) {
[venues release];
...
NSMutableArray *updatedVenues = [NSMutableArray array];
for (NSDictionary *venue in _venues) {
...
if (address != nil && city != nil) {
CLLocationCoordinate2D coord = CLLocationCoordinate2DMake([[_location objectForKey:#"lat"] floatValue], [[_location objectForKey:#"lng"] floatValue]);
CLLocation *currentLoc = [[CLLocation alloc] initWithLatitude:self.currentLocation.latitude longitude:self.currentLocation.longitude];
CLLocation *venueLoc = [[CLLocation alloc] initWithLatitude:coord.latitude longitude:coord.longitude];
CLLocationDistance distance = [venueLoc distanceFromLocation:currentLoc];
float miles = distance / 1000;
miles *= 0.621371192; // metres to miles
NSMutableDictionary *newLocation = [NSMutableDictionary dictionaryWithDictionary:_location];
[newLocation removeObjectForKey:#"distance"];
[newLocation setObject:[NSNumber numberWithFloat:miles] forKey:#"distance"];
_location = [NSDictionary dictionaryWithDictionary:newLocation];
...
NSMutableDictionary *newVenue = [NSMutableDictionary dictionaryWithDictionary:venue];
[newVenue removeObjectForKey:#"location"];
[newVenue setObject:_location forKey:#"location"];
[updatedVenues addObject:newVenue];
}
}
venues = [updatedVenues retain];
}
}
It looks like you need to sort by venue.location.distance:
[self.venues sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSNumber *distance1 = [[obj1 objectForKey:#"location"] objectForKey:#"distance"];
NSNumber *distance2 = [[obj2 objectForKey:#"location"] objectForKey:#"distance"];
return [distance1 compare:distance2];
}];
If you are using a version of Xcode >= 4.4 (4.5 for iOS) you could just do:
[self.venues sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1[#"location"][#"distance"] compare:obj2[#"location"][#"distance"]];
}];

Annotations on MapView: Coordinates

I have two NSStrings (address, and key) which contain the coordinates (longitude and latitude) in form of numbers (34,56789...):
NSString *key = [allKeys objectAtIndex:i];
NSObject *obj = [DictionaryMap objectForKey:key];
NSString *address = [NSString stringWithFormat:#"%#", obj];
CLLocationCoordinate2D anyLocation;
anyLocation.latitude = [address doubleValue];
anyLocation.longitude = [key doubleValue];
MKPointAnnotation *annotationPoint2 = [[MKPointAnnotation alloc] init]; annotationPoint2.coordinate = anyLocation;
annotationPoint2.title = #"Event";
annotationPoint2.subtitle = #"Microsoft's headquarters2";
[mapView addAnnotation:annotationPoint2];
...But I can't understand why it doesn't plot in the same point as the coordinates written. I think this doesn't work:
[address doubleValue]
So I tried replacing it with:
location.latitude = NSNumber/NSString
but it gives an error.
UPDATE:
IN VIEW DID LOAD:
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(handleLongPressGesture:)];
[self.mapView addGestureRecognizer:longPressGesture];
[mapView.userLocation setTitle:#"I am here"];
..then...
-(void)handleLongPressGesture:(UIGestureRecognizer*)sender {
// This is important if you only want to receive one tap and hold event
if (sender.state == UIGestureRecognizerStateEnded)
{
[self.mapView removeGestureRecognizer:sender];
}
else
{
// Here we get the CGPoint for the touch and convert it to latitude and longitude coordinates to display on the map
CGPoint point = [sender locationInView:self.mapView];
CLLocationCoordinate2D locCoord = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
// Then all you have to do is create the annotation and add it to the map
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init]; annotationPoint.coordinate = locCoord;
annotationPoint.title = #"Microsoft";
annotationPoint.subtitle = #"Microsoft's headquarters";
[mapView addAnnotation:annotationPoint];
NSString *latitude = [[NSString alloc] initWithFormat:#"%f",locCoord.latitude];
NSString *longitude = [[NSString alloc] initWithFormat:#"%f", locCoord.longitude];
NSLog(latitude);
NSLog(longitude);
[[NSUserDefaults standardUserDefaults]setObject:latitude forKey:#"FolderLatitude"];
[[NSUserDefaults standardUserDefaults]setObject:longitude forKey:#"FolderLongitude"];
}
}
...I then save the coordinates in a JSON file and then read them from the file.
Print out the values that you are setting for lat/lon. It sounds like these values are not being converted to double properly. If the strings are not in "xxx.xxx" format then they will not convert to doubles properly when you call doubleValue.
Finally I understood: This is the correct way to make it work:
NSString *myString = (string initialization here)
float stringFloat = [myString floatValue];
anyLocation.longitude = stringFloat;

Adding Annotations for coordinates MKMapView

I am parsing this JSON file (correctly, it works with the UITextFields):
{"longitude":["37.786793","39.388528"],"latitude":["-122.395416","-78.887734"]}
ind creating MapViews, with the respective annotations in this way:
NSArray *allKeys2 = [DictionaryMap allKeys];
for (int h = 0; h < [allKeys2 count]; h++) {
CGRect mapFrame = CGRectMake( 400, e, 200, 110);
MKMapView *mapView2 = [[MKMapView alloc] initWithFrame:mapFrame];
[image1 addSubview:mapView2];
NSString *key2 = [allKeys2 objectAtIndex:i];
NSObject *obj2 = [DictionaryMap objectForKey:key2];
NSString *address = [NSString stringWithFormat:#"%#", obj2];
float stringFloat = [address floatValue];
float stringFloat2 = [key2 floatValue];
CLLocationCoordinate2D anyLocation;
anyLocation.longitude = stringFloat;
anyLocation.latitude = stringFloat2;
MKPointAnnotation *annotationPoint2 = [[MKPointAnnotation alloc] init]; annotationPoint2.coordinate = anyLocation;
annotationPoint2.title = #"Event";
annotationPoint2.subtitle = #"Microsoft's headquarters2";
[mapView2 addAnnotation:annotationPoint2];
[mapView2.userLocation setTitle:#"I am here"];
[mapView2.userLocation addObserver:self
forKeyPath:#"location"
options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld)
context:NULL];
[mapView2 setShowsUserLocation:NO];
[MapViewArray addObject:mapView2];
if (MapViewArray == nil)MapViewArray = [[NSMutableArray alloc]init];
[MapViewArray addObject: mapView2];
}}
}while(g < f);
...I want the first map view to show the first coordinate pin, and the second to show the second pair of coordinates. But now, it is plotting on all the map views the same pin, corresponding to the last coordinates, and not to the first and second... respectively. This method works for the UITextField text, so I can't find the problem.
Please help!!
EDIT:
NSString *filenameMap = [NSString stringWithFormat:#"%#%#Map", destDir, NavBar.topItem.title];
NSString *MapPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#Map", NavBar.topItem.title]];
[self.restClient loadFile:filenameMap intoPath:MapPath];
NSString *fileContentMap = [[NSString alloc] initWithContentsOfFile:MapPath];
SBJsonParser *parserMap = [[SBJsonParser alloc] init];
NSDictionary *dataMap = (NSDictionary *) [parserMap objectWithString:fileContentMap error:nil];
NSArray *MaparrayLongitude = [dataMap objectForKey:#"longitude"];
NSArray *MaparrayLatitude = [dataMap objectForKey:#"latitude"];
NSDictionary* DictionaryMap = [NSDictionary dictionaryWithObjects:MaparrayLatitude forKeys:MaparrayLongitude];
Another take:
You probably don't want to map your latitudes to longitudes in DictionaryMap. How about making an NSArray of NSDictionaries, where each dictionary has a "latitude" key and a "longitude" key?
Also, you have "[MapViewArray addObject: mapView2]" twice in your code.
And what is "g"? Maybe add some logging to your loop so you can see what's being created?