gpt4 book ai didi

IOS 使用 CLLocationManager 从纬度/经度获取位置

转载 作者:行者123 更新时间:2023-11-28 22:49:27 26 4
gpt4 key购买 nike

我正在尝试从我之前在应用程序中获得的纬度/经度值反向地理编码位置,我想从这个坐标中找到城市名称、国家名称和 ISO。

我目前正在使用 CLLocationManager 通过以下代码获取实际位置信息:

//Auto geolocation and find city/country
locationManager.delegate=self;

//Get user location
[locationManager startUpdatingLocation];
[self.geoCoder reverseGeocodeLocation: locationManager.location completionHandler:
^(NSArray *placemarks, NSError *error) {

//Get nearby address
CLPlacemark *placemark = [placemarks objectAtIndex:0];

//String to hold address
locatedAtcountry = placemark.country;
locatedAtcity = placemark.locality;
locatedAtisocountry = placemark.ISOcountryCode;

//Print the location to console
NSLog(@"Estas en %@",locatedAtcountry);
NSLog(@"Estas en %@",locatedAtcity);
NSLog(@"Estas en %@",locatedAtisocountry);

[cityLabel setText:[NSString stringWithFormat:@"%@,",locatedAtcity]];
[locationLabel setText:[NSString stringWithFormat:@"%@",locatedAtcountry]];

//Set the label text to current location
//[locationLabel setText:locatedAt];

}];

它工作得很好,但是,可以从我已经保存在设备中的 Long/Lat 值而不是像实际代码中那样使用当前位置执行相同的操作?

更新及解决方案:

感谢 Mark 的回答,我最终使用以下代码从保存的坐标中获取信息:

 CLLocation *location = [[CLLocation alloc] initWithLatitude:37.78583400 longitude:-122.40641700];

[self.geoCoder reverseGeocodeLocation: location completionHandler:
^(NSArray *placemarks, NSError *error) {

//Get nearby address
CLPlacemark *placemark = [placemarks objectAtIndex:0];

//String to hold address
locatedAtcountry = placemark.country;
locatedAtcity = placemark.locality;
locatedAtisocountry = placemark.ISOcountryCode;

//Print the location to console
NSLog(@"Estas en %@",locatedAtcountry);
NSLog(@"Estas en %@",locatedAtcity);
NSLog(@"Estas en %@",locatedAtisocountry);

[cityLabel setText:[NSString stringWithFormat:@"%@",locatedAtcity]];
[locationLabel setText:[NSString stringWithFormat:@"%@",locatedAtcountry]];

//Set the label text to current location
//[locationLabel setText:locatedAt];

}];

最佳答案

是的。使用保存的纬度/经度值使用 initWithLatitude:longitude: 方法创建一个 CLLocation 对象,并将其传递给 reverseGeocodeLocation:

我很惊讶你说这是有效的(尽管,如果你在模拟器上,无论如何都会模拟位置服务,这可能就是原因)因为当你调用 startUpdatingLocation 时,你的实现像 locationManager:didUpdateToLocation:fromLocation: 这样的 CLLocationManagerDelegate 方法被调用。 (你已经实现了这些,对吗?)只有当这个(和其他)委托(delegate)方法被调用时,你才能确定你已经成功地确定了用户的位置。

您可能需要阅读有关 CLLocationManagerDelegate 协议(protocol)和 Location Services 的内容Apple 记录的最佳实践。

关于IOS 使用 CLLocationManager 从纬度/经度获取位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12306590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com