How to find address using latitude and longitude [duplicate] - iphone

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Convert iPhone GPS to address
hi,how to find address using latitude and longitude in iphonei

This is called "reverse geocoding". Here is a sample:
http://www.icodeblog.com/2009/12/22/introduction-to-mapkit-in-iphone-os-3-0-part-2/

import
#import "JSON.h"
I'm using json framework from
http://code.google.com/p/json-framework download that.
+(NSString *) getLocation:(double) lattitude logitude:(double) longitude
{
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",lattitude,longitude];
NSURL *urlFromString = [NSURL URLWithString:urlString];
NSStringEncoding encodingType = NSUTF8StringEncoding;
NSString *reverseGeoString = [NSString stringWithContentsOfURL:urlFromString encoding:encodingType error:nil];
NSDictionary *locationResult = [reverseGeoString JSONValue];
NSString *status = (NSString *)[locationResult objectForKey:#"status"];
NSString *retVal = nil;
if([status isEqualToString:#"OK"])
{
NSArray *results = [locationResult objectForKey:#"results"];
if([results count] > 0)
{
NSDictionary *address=[results objectAtIndex:0];
retVal = [address objectForKey:#"formatted_address"];
}
}
return retVal;
}

you can do this in 2 ways
1) CellIdentifier iphone example, its easy.
2) use a google map service from iphone, which can convert your address to Longitude and latitude here is the link
http://maps.google.com/maps/geo?q=###ADDRESS###&;output=###OUTPUT###&;key=###KEY###
Regards
Shahid

Related

How can I extract parameters from a non-standard URL NSString object?

I'm diving into iOS development and I have a custom URL scheme for my iPhone app that looks like myApp://?q=200. I have the following code to get the query parameter...
NSString *urlString = [url absoluteString];
NSString *query = [urlString stringByReplacingOccurrencesOfString:#"myApp://?q=" withString:#""];
...but I'd like to make it a bit more future-proof in the event that I add more parameters. How can I extract the "q" parameter in a safer way?
Thanks in advance for your wisdom!
You can split the query returned from the URL by & and = and put them in a dictionary.
NSURL *url = [NSURL URLWithString:#"myApp://?q=200"];
NSArray *query = [[url query] componentsSeparatedByString:#"&"];
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:[query count]];
for(NSString *parameter in query)
{
NSArray *kv = [parameter componentsSeparatedByString:#"="];
[parameters setObject:[kv count] > 1 ? [[kv objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding] : [NSNull null]
forKey:[[kv objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding]];
}
NSLog(#"Parameters: %#", parameters);
NSLog(#"q = %#", [parameters objectForKey:#"q"]);
In this example if there is no value for the parameter I just set it to NSNull. This means you would either need to check for NSNull or change the logic to skip keys with values or set them to an empty string.
This from the top of my head could work but doesnt yet include error checking the input
-(NSDictionary*) parameterDictionaryFromString: (NSURL*) url {
//input can be something like: "myApp://?q=one&q2=two&q3=three"
NSString *requestString = [url query];
//now we have q=one&q2=two&q3=three
NSArray *requests = [requestString componentsSeparatedByString: #"&"];
NSMutableDictionary *resultDictionary = [NSMutableDictionary dictionary];
for (NSString *singleParameter in requests) {
NSArray *keyValuePair = [singleParameter componentsSeparatedByString: #"="];
[resultDictionary setObject: [keyValuePair objectAtIndex: 1] forKey: [keyValuePair objectAtIndex: 0]];
}
NSURL *u = [NSURL URLWithString: #"myApp://something?q=1&check=yes"];
NSLog(#"paramStr = %#", [u parameterString]);
return [resultDictionary copy];
}
Break the Query String by Distinct Separator,
Assure Valued Content provided at index:1 (The right-hand side of the query string break)
In valued content then use downstream, or set to upstream variable.
//Your Example:
//#"myApp://?q=200"
//Break:
NSArray *queryParts = [urlString componentsSeparatedByString:#"?q="];
//Assure Content:
if ([[array objectAtIndex:1] length]>0) {
//Setter:
NSString *queryString = [array objectAtIndex:1];
//... Use away...
}
The key is to leverage the NSArray class over StringReplace.

Registration timer expired, but client is still registering! - Google geocoding error

I am trying to use these two lines to get lat/long info when given an address input.
NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv", theAddress];
NSString *locationString = [[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:urlString]] autorelease];
It is weird that sometimes I get the lat, long info as quick as in 5 seconds and in other cases the app is stuck for about 5 mins and then it logs an error stating "Registration timer expired, but client is still registering!"
It also gives the location info (ie result string wth lat/long info) as null.
I tried it a number of times and couldn't figure out what makes it work and what doesn't.
Has anybody encountered the same issue before or any advice on this pls.
Thanks
try below code its working fine with me.
CLLocationCoordinate2D coord=[self gettingLatandLonFromAddress:address];
-(CLLocationCoordinate2D ) gettingLatandLonFromAddress:(NSString *)address
{
CLLocationCoordinate2D currentLoc;
NSString *urlString=[NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv",[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationString=[NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:nil];
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{
NSLog(#"Error");
}
currentLoc.latitude=latitude;
currentLoc.longitude=longitude;
return currentLoc;
}

How to sort NSArray? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to sort a NSArray alphabetically?
I am using below code to load data into UITableView from NSArray.
How can I sort them in alphabetical order ?
Mine is NSArray not NSMutableArray nor I am using Dictionary
defaultVot = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathToVot error:&error];
NSString *fileName = [[defaultVot objectAtIndex:indexPath.row-1] lastPathComponent];
NSString *filenameWithoutExtension = [fileName substringToIndex:[fileName length] -4];
cell.textLabel.text = filenameWithoutExtension;
You should probably sort your array earlier. (Likely when you load the list.) Then use the sorted array as the datasource.
NSArray * defaultVot = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathToVot error:&error];
NSMutableArray * array = [NSMutableArray arrayWithCapacity:[defaultVot count]];
for (NSString * f in defaultVot){
NSString *fileName = [f lastPathComponent];
NSString *filenameWithoutExtension = [fileName substringToIndex:[fileName length] -4];
[array addObject:filenameWithoutExtension];
}
NSArray * sortedArray = [array sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
sortedArray = [yourArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
Check this
And also this
You can see Apple's documentation on how to accomplish this.
As an example:
// From the Documentation
sortedArray =
[anArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
This will return a new array that is sorted using the rules for the current locale (in a case insensitive manner).

How to parse an asset URL in Objective-c?

The iPhone UIImagePickerControllerReferenceURL returns an URL as:
assets-library://asset/asset.PNG?id=1000000001&ext=PNG
What's the best (preferably simple) way to retrive 1000000001 and PNG as NSStrings from the above URL example?
Well, you can easily turn it into an NSURL by using +[NSURL URLWithString:]. From there you could grab the -query string and parse it out, something like this:
NSString *query = ...;
NSArray *queryPairs = [query componentsSeparatedByString:#"&"];
NSMutableDictionary *pairs = [NSMutableDictionary dictionary];
for (NSString *queryPair in queryPairs) {
NSArray *bits = [queryPair componentsSeparatedByString:#"="];
if ([bits count] != 2) { continue; }
NSString *key = [[bits objectAtIndex:0] stringByRemovingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *value = [[bits objectAtIndex:1] stringByRemovingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[pairs setObject:value forKey:key];
}
NSLog(#"%#", pairs);
Warning, typed in a browser, so some of my spellings may be wrong.
For IOS >= 4.0 you can use native regular expressions with NSRegularExpression class. Examples you can find here

iPhone parsing url for GET params

I have an string which is got from parsing an xml site.
http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500
I want to have an NSString function that will be able to parse the value of c.
Is there a default function or do i have to write it manually.
You could use Regular expression via RegExKit Lite:
http://regexkit.sourceforge.net/RegexKitLite/
Or you could separate the string into components (which is less nice):
NSString *url=#"http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500";
NSArray *comp1 = [url componentsSeparatedByString:#"?"];
NSString *query = [comp1 lastObject];
NSArray *queryElements = [query componentsSeparatedByString:#"&"];
for (NSString *element in queryElements) {
NSArray *keyVal = [element componentsSeparatedByString:#"="];
if (keyVal.count > 0) {
NSString *variableKey = [keyVal objectAtIndex:0];
NSString *value = (keyVal.count == 2) ? [keyVal lastObject] : nil;
}
}
I made a class that does this parsing for you using an NSScanner, as an answer to the same question a few days ago. You might find it useful.
You can easily use it like:
URLParser *parser = [[[URLParser alloc] initWithURLString:#"http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500"] autorelease];
NSString *c = [parser valueForVariable:#"c"]; //c=500
Try the following:
NSURL *url = [NSURL URLWithString:#"http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500"];
NSMutableString *parameterString = [NSMutableString stringWithFormat:#"{%#;}",[url parameterString]];
[parameterString replaceOccurrencesOfString:#"&" withString:#";"];
// Convert string into Dictionary
NSPropertyListFormat format;
NSString *error;
NSDictionary *paramDict = [NSPropertyListSerialization propertyListFromData:[parameterString dataUsingEncoding:NSUTF8StringEncoding] mutabilityOption: NSPropertyListImmutable format:&format errorDescription:&error];
// Now take the parameter you want
NSString *value = [paramDict valueForKey:#"c"];
Here is the native iOS approach using NSURLComponents and NSURLQueryItem classes:
NSString *theURLString = #"http://www.arijasoft.com/givemesomthing.php?a=3434&b=435edsf&c=500";
NSArray<NSURLQueryItem *> *theQueryItemsArray = [NSURLComponents componentsWithString:theURLString].queryItems;
for (NSURLQueryItem *theQueryItem in theQueryItemsArray)
{
NSLog(#"%# %#", theQueryItem.name, theQueryItem.value);
}