我根据经度和纬度值获得了当前位置,然后我还使用Annotation在Google地图上获得了多个位置。现在我想得到基于地址(即街道,城市和县)的经度和纬度值。需要一些指导如何实现。
直到现在,这是我尝试过的: -
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize streetField = _streetField, cityField = _cityField, countryField = _countryField, fetchCoordinatesButton = _fetchCoordinatesButton, nameLabel = _nameLabel, coordinatesLabel = _coordinatesLabel;
@synthesize geocoder = _geocoder;
- (void)viewDidLoad
{
[super viewDidLoad];
_streetField.delegate=self;
_cityField.delegate=self;
_countryField.delegate=self;
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)fetchCoordinates:(id)sender {
NSLog(@"Fetch Coordinates");
if (!self.geocoder) {
NSLog(@"Geocdoing");
self.geocoder = [[CLGeocoder alloc] init];
}
NSString *address = [NSString stringWithFormat:@"%@ %@ %@", self.streetField.text, self.cityField.text, self.countryField.text];
NSLog(@"GET Addres%@",address);
self.fetchCoordinatesButton.enabled = NO;
[self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(@"Fetch Gecodingaddress");
if ([placemarks count] > 0) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"GET placemark%@",placemark);
CLLocation *location = placemark.location;
NSLog(@"GET location%@",location);
CLLocationCoordinate2D coordinate = location.coordinate;
self.coordinatesLabel.text = [NSString stringWithFormat:@"%f, %f", coordinate.latitude, coordinate.longitude];
NSLog(@"CoordinatesLabel%@",self.coordinatesLabel.text);
if ([placemark.areasOfInterest count] > 0) {
NSString *areaOfInterest = [placemark.areasOfInterest objectAtIndex:0];
self.nameLabel.text = areaOfInterest;
NSLog(@"NameLabe%@",self.nameLabel.text);
}
}
self.fetchCoordinatesButton.enabled = YES;
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
@end
上面的代码不能给我经纬度。需要帮助我在这里做错了什么,或者我是否缺少某些东西。
先谢谢。
答案 0 :(得分:25)
修改强>:
在iOS8更新中使用此检查之前
NSLocationAlwaysUsageDescription
NSLocationWhenInUseUsageDescription
这是为了获得基于纬度和长度的用户区域,如街道名称,州名,国家。
-(CLLocationCoordinate2D) getLocationFromAddressString: (NSString*) addressStr {
double latitude = 0, longitude = 0;
NSString *esc_addr = [addressStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];
NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
if (result) {
NSScanner *scanner = [NSScanner scannerWithString:result];
if ([scanner scanUpToString:@"\"lat\" :" intoString:nil] && [scanner scanString:@"\"lat\" :" intoString:nil]) {
[scanner scanDouble:&latitude];
if ([scanner scanUpToString:@"\"lng\" :" intoString:nil] && [scanner scanString:@"\"lng\" :" intoString:nil]) {
[scanner scanDouble:&longitude];
}
}
}
CLLocationCoordinate2D center;
center.latitude=latitude;
center.longitude = longitude;
NSLog(@"View Controller get Location Logitute : %f",center.latitude);
NSLog(@"View Controller get Location Latitute : %f",center.longitude);
return center;
}
根据你的项目
在viewdidload方法或某个地方调用这样的方法[self getLocationFromAddressString:@"chennai"];
只需在浏览器中传递此内容即可 http://maps.google.com/maps/api/geocode/json?sensor=false&address=chennai
你将拥有lat和lon的json格式
http://maps.google.com/maps/api/geocode/json?sensor=false&address=@"your city name here"
NSString *address = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@ %@ %@", self.streetField.text, self.cityField.text, self.countryField.text];
这种方法的用法......
CLLocationCoordinate2D center;
center=[self getLocationFromAddressString:@"uthangarai"];
double latFrom=¢er.latitude;
double lonFrom=¢er.longitude;
NSLog(@"View Controller get Location Logitute : %f",latFrom);
NSLog(@"View Controller get Location Latitute : %f",lonFrom);
答案 1 :(得分:4)
<强>夫特强>
public func getLocationFromAddress(address : String) -> CLLocationCoordinate2D {
var lat : Double = 0.0
var lon : Double = 0.0
do {
let url = String(format: "https://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", (address.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!))
let result = try Data(contentsOf: URL(string: url)!)
let json = JSON(data: result)
lat = json["results"][0]["geometry"]["location"]["lat"].doubleValue
lon = json["results"][0]["geometry"]["location"]["lng"].doubleValue
}
catch let error{
print(error)
}
return CLLocationCoordinate2D(latitude: lat, longitude: lon)
}
我使用了SwiftyJSON,但您可以根据需要解析JSON响应
答案 2 :(得分:3)
试试这个,
NSString *address = [NSString stringWithFormat:@"%@,%@,%@", self.streetField.text, self.cityField.text,self.countryField.text];
[self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error)
{
if(!error)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"%f",placemark.location.coordinate.latitude);
NSLog(@"%f",placemark.location.coordinate.longitude);
NSLog(@"%@",[NSString stringWithFormat:@"%@",[placemark description]]);
}
else
{
NSLog(@"There was a forward geocoding error\n%@",[error localizedDescription]);
}
}
];
答案 3 :(得分:0)
- (IBAction)forwardButton:(id)sender
{
if([self.address.text length])
{
NSString *place = self.address.text;
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
__unsafe_unretained RTGeoCoderViewController *weakSelf = self;
[geocoder geocodeAddressString:place completionHandler:^(NSArray* placemarks, NSError* error)
{
NSLog(@"completed");
if ( error )
{
NSLog(@"error = %@", error );
dispatch_async(dispatch_get_main_queue(),
^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[self errorMessage:error.code] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alert show];
});
}
else
{
NSLog(@"%@",placemarks);
}
}];
}
}
答案 4 :(得分:0)
试试这个
- (void)getAddressFromAdrress:(NSString *)address withCompletationHandle:(void (^)(NSDictionary *))completationHandler {
CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
//Get the address through geoCoder
[geoCoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
if ([placemarks count] > 0 && !error) {
//get the address from placemark
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
CLLocation *location = placemark.location;
CLLocationCoordinate2D coordinate = location.coordinate;
_latitudeUserLocation = coordinate.latitude;
_longitudeUserLocation = coordinate.longitude;
NSString *postalCode = placemark.addressDictionary[(NSString*)kABPersonAddressZIPKey];
if (postalCode == nil) postalCode = @"";
if (locatedAt == nil) locatedAt = @"";
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
postalCode ,kPostalCode,
locatedAt ,kFullAddress,
nil];
completationHandler(dictionary);
} else {
completationHandler(nil);
}
}];
}