开发者

Google Maps http request not working

开发者 https://www.devze.com 2023-01-12 18:59 出处:网络
I am trying to use an http request to google maps to obtain the driving distance between two locations using JSON. However, it seems these are treated different in a browser than in the (iphone) app.

I am trying to use an http request to google maps to obtain the driving distance between two locations using JSON. However, it seems these are treated different in a browser than in the (iphone) app.

I create an NSString which holds the URL, using coordinates and %20 (a space). I NSLog() the URL to make sure, and it seems ok (ie it works fine in browser and looks fine)...but when NSLogging the string initialised with the contents of that URL, I get (null).

Here is the code:

NSString *urlString=[[NSString alloc] initWithFormat:@"http://maps.google.com/maps/nav?q=from:%.7f%@%.7f%@to:%.7f%@%.7f", testLocation.coordinate.latitude, @"%%20", testLocation.coordinate.longitude, @"%%20", thePark.coordinate.latitude, @"%%20", thePark.coordinate.longitude];

which I then NSLog() and get http://maps.google.com/m开发者_StackOverflowaps/nav?q=from:51.4986110%20-0.1236110%20to:51.4960938%20-0.2200041 ...to no avail.

NSString *json=[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:urlString]];

When I NSLog() this, it prints null. Does anyone have any suggestions as to why this might be happening or an easier way to do it? I plan to then parse the JSON and get the drving distance


You should escape the urlString using "stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding" instead of escaping manually with %20.


Edit:

I tested with these 3 lines of codes and I got the json string.

NSString *urlString=[[[[NSString alloc] initWithFormat:@"http://maps.google.com/maps/nav?q=from:%.7f %.7f to:%.7f %.7f", 51.4986110, -0.1236110, 51.4960938, -0.2200041] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] autorelease];

NSString *json=[[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:urlString]] autorelease];
NSLog(@"json = %@", json);
0

精彩评论

暂无评论...
验证码 换一张
取 消