I am trying to create an autocomplete addresses suggestion using JSON.
The problem that I am facing is that I can get the latitude and longitude from a the user types on the UISearchDisplay. However I am trying to parse this data to addresses names. I was trying to use reverse geocoding from Apple but with no success. I am receiving only one value.
I was using apple geocoding straight away but the results were not what I was expecting.
Here is the code:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
NSError *error;
NSString *lookUpString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true", self.searchBar.text];
lookUpString = [lookUpString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSData *jsonResponse = [NSData dataWithContentsOfURL:[NSURL URLWithString:lookUpString]];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];
self.locationArray = [[[jsonDict valueForKey:#"results"] valueForKey:#"geometry"] valueForKey:#"location"];
int total = self.locationArray.count;
for (int i = 0; i < total - 1; i++)
{
NSLog(#"locationArray count: %d", self.locationArray.count);
NSArray *localLocations;
localLocations = [self.locationArray objectAtIndex:i];
NSLog(#"%d",i);
NSString *latitudeString = [localLocations valueForKey:#"lat"];
NSString *longitudeString = [localLocations valueForKey:#"lng"];
NSLog(#"LatitudeString:%# & LongitudeString:%#", latitudeString, longitudeString);
NSString *statusString = [jsonDict valueForKey:#"status"];
NSLog(#"JSON Response Status:%#", statusString);
double latitude = 0.0;
double longitude = 0.0;
latitude = [latitudeString doubleValue];
longitude = [longitudeString doubleValue];
CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error){
[[self placemarks] addObject:placemarks];
NSLog(#"PLACEMARKS %d", self.placemarks.count);
}];
}
NSLog(#"Mutable array %d", self.placemarks.count);
[self.searchDisplayController.searchResultsTableView reloadData];
return NO;
}
The NSLog(#"PLACEMARKS %d", self.placemarks.count); only display once, in the end of the task.
Any suggestions?
I really was doing so much more than the necessary.
Here is my code now:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
NSError *error;
NSString *lookUpString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&components=country:AU&sensor=false", self.searchBar.text];
lookUpString = [lookUpString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSData *jsonResponse = [NSData dataWithContentsOfURL:[NSURL URLWithString:lookUpString]];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];
self.locationArray = [[jsonDict valueForKey:#"results"] valueForKey:#"geometry"];
int total = self.locationArray.count;
NSLog(#"locationArray count: %d", self.locationArray.count);
for (int i = 0; i < total; i++)
{
NSString *statusString = [jsonDict valueForKey:#"status"];
NSLog(#"JSON Response Status:%#", statusString);
NSLog(#"Address: %#", [self.locationArray objectAtIndex:i]);
}
[self.searchDisplayController.searchResultsTableView reloadData];
return NO;
}
Related
I am trying to parse an NSString to NSArray but couldn't get any success. Here is my String: NSString *points = #"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
I want this string mapped to NSArray.
NSArray *tempArray = points;
OK, code golf (untested):
NSString *points = #"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
NSError *error = nil;
NSArray *pointsArray = [NSJSONSerialization JSONObjectWithData:[points dataUsingEncoding:NSUTF8StringEncoding]
options:kNilOptions
error:&error];
for (NSArray *point in pointsArray) {
NSAssert([point count] == 2, #"Invalid point");
// do thing with point
CGPoint pt = CGPointMake([point[0] floatValue], [point[1] floatValue]);
}
Can you plz try this, May it solve your problem,
NSString *points = #"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
NSArray* arrayOfStrings = [points componentsSeparatedByString:#","];
NSLog(#"%#",arrayOfStrings);
NSMutableArray *copyArray = [arrayOfStrings mutableCopy];
NSMutableString *stringFirst = (NSMutableString *)[copyArray objectAtIndex:0];
NSMutableString *stringLast = (NSMutableString *)[copyArray lastObject];
stringFirst=[stringFirst substringFromIndex:1];
stringLast=[stringLast substringToIndex:stringLast.length-1];
[copyArray replaceObjectAtIndex:0 withObject:stringFirst];
[copyArray replaceObjectAtIndex:(copyArray.count-1) withObject:stringLast];
NSMutableArray *yourarray = [[NSMutableArray alloc] init];
for (int i=0; i<=(copyArray.count/2); i+=2) {
[yourarray addObject:[NSString stringWithFormat:#"%#,%#",[copyArray objectAtIndex:i], [copyArray objectAtIndex:i+1]]];
}
NSLog(#"%#",yourarray);
Happy Coding!!
That string looks like JSON so you can use NSJSONSerialization
NSData * data = [points dataUsingEncoding: NSUTF8StringEncoding];
NSError * error = nil;
NSArray * arrayOfPointArrays = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
I am using Google map iOS sdk for getting direction.By this LINK help me to draw route between two points.Now i cannot give route instruction (e.g.: Turn Left,Turn right) to the end user. How to solve this issue?Please help me.Now i am using following code
//Request the url
-(void)getWayPoints:(CLLocationCoordinate2D )origin destinationIS:(CLLocationCoordinate2D)desti{
NSString *oLat = [NSString stringWithFormat:#"%f",origin.latitude];
NSString *oLong = [NSString stringWithFormat:#"%f",origin.longitude];
NSString *dLat = [NSString stringWithFormat:#"%f",desti.latitude];
NSString *dLong = [NSString stringWithFormat:#"%f",desti.longitude];
NSString *url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?&origin=%#,%#&destination=%#,%#&sensor=false",oLat,oLong,dLat,dLong];
NSLog(#"url : %#", url);
CLLocationCoordinate2D position = CLLocationCoordinate2DMake(
origin.latitude,
origin.longitude);
GMSMarker *marker = [GMSMarker markerWithPosition:position];
marker.map = mapView_;
CLLocationCoordinate2D position1 = CLLocationCoordinate2DMake(
desti.latitude,
desti.longitude);
GMSMarker *marker1 = [GMSMarker markerWithPosition:position1];
marker1.map = mapView_;
NSURL *googleRequestURL=[NSURL URLWithString:url];
NSLog(#"googleRequestURL : %#", googleRequestURL);
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
//Response from URL
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
// NSLog(#"responseData Data: %#", responseData);
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray* places = [json objectForKey:#"routes"];
NSDictionary *routes = [json objectForKey:#"routes"][0];
NSDictionary *route = [routes objectForKey:#"overview_polyline"];
NSArray *routes1 = [json objectForKey:#"routes"];
NSArray *legs = [routes1[0] objectForKey:#"legs"];
NSLog(#"legs %#", legs);
NSArray *steps = [legs[0] objectForKey:#"steps"];
NSString *overview_route = [route objectForKey:#"points"];
GMSPath *path = [GMSPath pathFromEncodedPath:overview_route];
GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
polyline.strokeColor = [UIColor redColor];
polyline.strokeWidth = 5.f;
polyline.map = mapView_;
}
NSString *str=[NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%#&sensor=false",self.txtFrom.text,self.txtTo.text];
NSURL *url=[[NSURL alloc]initWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray* latestLoans = [json objectForKey:#"routes"];
NSMutableDictionary *legs=[[[latestLoans objectAtIndex:0] objectForKey:#"legs"] objectAtIndex:0];
NSString *startLocation,*endLocation,*totalDistance,*totalDuration;
CLLocationCoordinate2D startLoc,endLoc;
startLocation = [legs objectForKey:#"start_address"];
endLocation = [legs objectForKey:#"end_address"];
totalDistance = [[legs objectForKey:#"distance"] objectForKey:#"text"];
totalDuration = [[legs objectForKey:#"duration"] objectForKey:#"text"];
startLoc=CLLocationCoordinate2DMake([[[legs objectForKey:#"start_location"] objectForKey:#"lat"] doubleValue], [[[legs objectForKey:#"start_location"] objectForKey:#"lng"] doubleValue]);
endLoc=CLLocationCoordinate2DMake([[[legs objectForKey:#"end_location"] objectForKey:#"lat"] doubleValue], [[[legs objectForKey:#"end_location"] objectForKey:#"lng"] doubleValue]);
NSArray *steps=[legs objectForKey:#"steps"];
NSMutableDictionary *tempDict;
if ([steps count]!=0) {
MKMapPoint* pointArr = malloc(sizeof(CLLocationCoordinate2D) * [steps count]+2);
[tv setText:#""];
for(int idx = 0; idx < [steps count]+2; idx++)
{
CLLocationCoordinate2D workingCoordinate;
if (idx==0) {
workingCoordinate=startLoc;
MKMapPoint point = MKMapPointForCoordinate(workingCoordinate);
pointArr[idx] = point;
[tv setText:[NSString stringWithFormat:#"%# %#",tv.text,#"START"]];
}
else if (idx==[steps count]+1){
workingCoordinate=endLoc;
MKMapPoint point = MKMapPointForCoordinate(workingCoordinate);
pointArr[idx+1] = point;
[tv setText:[NSString stringWithFormat:#"%# %#",tv.text,#"\nEND"]];
}
else{
MKPolyline *pol= [self polylineWithEncodedString:[[[steps objectAtIndex:idx-1] objectForKey:#"polyline"] objectForKey:#"points"]];
MKMapPoint point = *(pol.points);
pointArr[idx] = point;
[tv setText:[NSString stringWithFormat:#"%#\n\n%#",tv.text,[self flattenHTML:[[steps objectAtIndex:idx-1] objectForKey:#"html_instructions"]]]];
}
tempDict = nil;
}
// create the polyline based on the array of points.
[mapView removeOverlay:routeLine];
routeLine = [MKPolyline polylineWithPoints:pointArr count:[steps count]];
[mapView addOverlay:routeLine];
free(pointArr);
}
with following supporting methods:
-(NSArray*) calculateRoutesFrom:(NSString *) f to: (NSString ) t { NSString apiUrlStr = [NSString stringWithFormat:#"http://maps.google.com/maps?output=dragdir&saddr=%#&daddr=%#", f, t];
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSLog(#"api url: %#", apiUrl);
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSUTF8StringEncoding error:nil];
#try {
// TODO: better parsing. Regular expression?
NSInteger a = [apiResponse indexOf:#"points:\"" from:0];
NSInteger b = [apiResponse indexOf:#"\",levels:\"" from:a] - 10;
NSInteger c = [apiResponse indexOf:#"tooltipHtml:\"" from:0];
NSInteger d = [apiResponse indexOf:#"(" from:c];
NSInteger e = [apiResponse indexOf:#")\"" from:d] - 2;
NSString* info = [[apiResponse substringFrom:d to:e] stringByReplacingOccurrencesOfString:#"\\x26#160;" withString:#""];
NSLog(#"tooltip %#", info);
NSString* encodedPoints = [apiResponse substringFrom:a to:b];
return [self decodePolyLine:[encodedPoints mutableCopy]];
}
#catch (NSException * e) {
// TODO: show error
}
}
I currently am pulling directions from google and storing them into an array. I then have an integer for the amount of directions found, and have the forloop displaying them via NSLog properly (with the html included)
My question is, how do I make this into a UIWebView so that it properly displays this information in a list?
Here is my code so far:
NSError *error;
NSString *currentLoc = #"Hyannis, MA";
NSString *directionsString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%#, %#, %#&sensor=false", currentLoc, [self.selectedEvent objectForKey:#"eventAddress"], [self.selectedEvent objectForKey:#"eventCity"], [self.selectedEvent objectForKey:#"eventState"]];
directionsString = [directionsString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSData *jsonResponse = [NSData dataWithContentsOfURL:[NSURL URLWithString:directionsString]];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];
self.directionsArray = [[[[jsonDict valueForKey:#"routes"] valueForKey:#"legs"] valueForKey:#"steps"] valueForKey:#"html_instructions"];
NSUInteger total = [self.directionsArray count];
for (int i = 0; i < total; i++)
{
NSString *statusString = [jsonDict valueForKey:#"status"];
NSLog(#"JSON Response Status:%#", statusString);
NSLog(#"Direction: %#", [self.directionsArray objectAtIndex:i]);
}
Hello friends
Google-map-SDK
I am new to ios and working on the GOOGLE-MAP-SDK. and everything is going very well,but i am not able to use the annotations in this case due to which i am not able to locate my positions which i fetched from the placeAPI of the google.
So kindly help me out with my errors.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Code File
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-(IBAction)search:(id)sender
{
NSString *url = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=30.7343000,76.7933000&radius=500&types=food&name&sensor=true&key=AIzaSyCGeIN7gCxU8baq3e5eL0DU3_JHeWyKzic"];
//Formulate the string as URL object.
NSURL *googleRequestURL=[NSURL URLWithString:url];
// Retrieve the results of the URL.
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
//The results from Google will be an array obtained from the NSDictionary object with the key "results".
NSArray* places = [json objectForKey:#"results"];
//Write out the data to the console.
NSLog(#"Google Data: %#", places);
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here is the code from which i will recive the data and want to display it on the googlemap.
NSLog(#"Google Data: %#", places); is giving me the out put...
...
NSArray *markerForplaces = [NSMutableArray arrayWithCapacity:[responseResults count]];
for (NSDictionary *dict in responseResults) {
GMSMarker *markerForplace = [self markerForGooglePlaceFromDictionary:dict error:nil];
if (markerForplace) {
[markerForplaces addObject:markerForplace];
markerForplace.map = self.mapView;
}
}
...
- (GMSMarker*)markerForGooglePlaceFromDictionary:(NSDictionary*)dict {
CLLocationCoordinate2D coordinate = [self coordinateForPlace:dict];
GMSMarker *marker = [GMSMarker markerWithPosition:coordinate];
marker.userInfo = dict; //save place
}
- (CLLocationCoordinate2D)coordinateForPlace:(NSDictionary*)dictionary {
NSDictionary *geo = [dictionary objectForKey:#"geometry"];
if ([geo isKindOfClass:[NSDictionary class]]) {
NSDictionary *loc = [geo objectForKey:#"location"];
if ([loc isKindOfClass:[NSDictionary class]]) {
NSString *lat = [loc objectForKey:#"lat"];
NSString *lng = [loc objectForKey:#"lng"];
return CLLocationCoordinate2DMake([lat doubleValue], [lng doubleValue]);
}
}
return CLLocationCoordinate2DMake(0, 0);
}
Please help me debug this code
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:#"http://cnapi.iconnectgroup.com/api/UserProfile?id=1"]];
NSString *json = [NSString stringWithContentsOfURL:urls encoding:NSASCIIStringEncoding error:&error];
NSLog(#"JSon data = %# and Error = %#", json, error);
if(!error)
{
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSLog(#"JSON data is :: %#", myJsonArray);
for(NSDictionary *jsonDictionary in myJsonArray)
{
//NSString *uids = jsonDictionary[#"UID"];
NSString *address1 = jsonDictionary[#"Address1"];
NSString *address2 = jsonDictionary[#"Address2"];
NSString *city = jsonDictionary[#"City"];
NSString *emailId = jsonDictionary[#"EmailID"];
NSString *fname = jsonDictionary[#"FName"];
NSString *fax = jsonDictionary[#"Fax"];
NSString *lname = jsonDictionary[#"LName"];
NSString *password = jsonDictionary[#"Password"];
NSString *phone = jsonDictionary[#"Phone"];
NSString *state = jsonDictionary[#"State"];
NSString *uids = [jsonDictionary objectForKey:#"UID"];
NSString *zip = jsonDictionary[#"Zip"];
NSString *company = jsonDictionary[#"company"];
NSString *department = jsonDictionary[#"department"];
NSLog(#"Uid is = %#", uids);
NSLog(#"First Name = %#", fname );
NSLog(#"Last Name = %#", lname);
NSLog(#"Company = %#", company);
NSLog(#"Email Id = %#", emailId);
NSLog(#"Password = %#", password);
NSLog(#"Department = %#", department);
NSLog(#"Address 1 = %#", address1);
NSLog(#"Address 2 = %#", address2);
NSLog(#"City = %#", city);
NSLog(#"State = %#", state);
NSLog(#"Zip = %#", zip);
NSLog(#"Phone = %#", phone);
NSLog(#"Fax = %#", fax);
}
}
});
[activity stopAnimating];
self.activity.hidden = YES;
}
Image will give you where the error is. I get this error after clicking stepover to debug. I also tried
NSString *address1 = [jsonDictionary objectForKey:#"Address1"];
From the output of url, it shows it's not array but a dictionary. You are trying to convert to array here.
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
instead use this
NSDictionary *myJsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
then remove that for loop no need of it. and replace your variable jsonDictionary with myJsonDictionary so to retrieve values.
// for(NSDictionary *jsonDictionary in myJsonArray)
Run now it will be fine. Worked for me fine
If the output was array of Dictionaries it would have been looked like this with square brackets around.
For Ex: [{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
If you are not sure of nature of response from url you can check for
the type. For ex:
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(#"its an array!");
NSArray *myJsonArray = (NSArray *)jsonObject;
// Handle Array of Dictionary
for(NSDictionary *jsonDictionary in myJsonArray)
{
NSString *address1 = jsonDictionary[#"Address1"];
//and so on
}
}
else {
NSLog(#"It's Dictionary");
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSLog(#"jsonDictionary - %#",jsonDictionary);
//Handle NSDictionary
}
jsonDictonary is a NSString not as you expect NSDictonary.
Double check your JSON and maybe before calling that function check if it's NSDictonary.
Your should use one of the semi-standard frameworks for parsing JSON into Core Data. There are some SO questions about those.
In this case, your JSON has only one object which is not an array.
In general, your app shouldn't abort if server sent something unexpected, so it's better to use a parser which will loudly complain about malformed JSON than with it from scratch.