This is the 16th day of my participation in the August More Text Challenge. For details, see “juejin.cn/post/698796…
preface
Key points of this article:
- positioning
- geocoding
- Determine if the target latitude and longitude are on the continent
Judge by latitude and longitude. Use Autonavi SDK for judgment. (Reverse geocoding for latitude and longitude if you enter the location manually)
I, geocode: geocode
- Set autonavi SDK apiKey
[AMapServices sharedServices].apiKey = @"xxx";
Copy the code
1.1 Geocoding API service address
Restapi.amap.com/v3/geocode/…
1.2 Application Scenarios
- Geocoding: translates detailed structured addresses into Autonautic latitude and longitude coordinates. In addition, the name of landmark scenic spots and buildings can be resolved into the longitude and latitude coordinates of Gaode.
1. Structured address: No. 6 futong East Street, Chaoyang District, Beijing 116.480881,39.989410 2. Landmark building: Tian ‘anmen Square 116.397499,39.908722
- Reverse geocoding: converts latitude and longitude into detailed structured addresses, and returns POI and AOI information in the vicinity.
Address description: 6 Futong East Street, Chaoyang District, Beijing
1.3 Structured address information address
Request parameter requirements
-
Rules to follow: country, province, city, district, county, town, village, street, door number, estate, building, such as: Beijing Chaoyang District Futong East Street 6.
-
In addition, the API’s specific requirements for addresses are:
Definition of structured address: First, address must be a string of characters, including country, province, city, district, county, town, village, street, house number, estate, building name. According to the characters grouped together from the large area name to the small area name. A valid address should be unique. Note: National information can be selectively ignored in geocoding conversion of mainland China, Hong Kong and Macao, but address composition at the level of province, city and town cannot be ignored. The detailed address information of Taiwan Province cannot be returned temporarily.
- If the request parameters are not accurate, handle the exception
CRMgeoDto *dto = [CRMgeoDto mj_objectWithKeyValues:responseObject];
if(dto.status.integerValue == 1) {// Obtain the latitude and longitude, if the failure, prompt [failed to obtain latitude and longitude, please enter the accurate business address!]
void (^noLocationdataBlock)(void) = ^void(void) {
[SVProgressHUD showInfoWithStatus:@" Failed to obtain latitude and longitude, please enter the correct business address!"];
};
// responseObject: {
// status = 1;
// info = OK;
// infocode = 10000;
// count = 0;
// geocodes = (
/ /);
if(dto.geocodes.count<=0){
noLocationdataBlock();
return ;
}
CRMgeocodesDto *geocodesDto = dto.geocodes.firstObject;
if([NSStringQCTtoll isBlankString:geocodesDto.location]){
noLocationdataBlock();
return ;
}
NSArray *array = [responseObject[@"geocodes"] [0] [@"location"] componentsSeparatedByString:@ ","];
if(array.count<=1){
noLocationdataBlock();
return;
}
Copy the code
1.4 Format returned by the interface
-
The returned DTO model definition
-
location
location = "114.468664, 38.037057,";
Copy the code
2020- 04- 10 11:43:29.914038+0800 Housekeeper[943:136269] responseObject: {
count = 1;
geocodes = (
{
adcode = 350503;
building = {
name = (
);
type = (
);
};
city = "\U6cc9\U5dde\U5e02";
citycode = 0595;
country = "\U4e2d\U56fd";
district = "\U4e30\U6cfd\U533a";
"formatted_address" = "\U798f\U5efa\U7701\U6cc9\U5dde\U5e02\U4e30\U6cfd\U533a\U5bcc\U5927\U53a6";
level = "\U5174\U8da3\U70b9";
location = "118.620285, 24.908597,";
neighborhood = {
name = (
);
type = (
);
};
number = (
);
province = "\U798f\U5efa\U7701"; street = ( ); township = ( ); }); info = OK; infocode =10000;
status = 1;
}
Copy the code
1.5 Determine whether it is in the mainland by inverse geocoding
To determine whether a target longitude and latitude in mainland China: kunnan.blog.csdn.net/article/det…
Judge by latitude and longitude. Use Autonavi SDK for judgment. (Reverse geocoding for latitude and longitude if you enter the location manually)
II, positioning
2.1 Obtaining Location Information
- Method of use
[[ProjectMethod shareProjectMethod] SingleLocation:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
[[QCT_Common getCurrentVC] hideHUD];
// Failed to locate
if (error)
{
if (error.code == AMapLocationErrorLocateFailed)
{
return;
}
NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
NSString *UserInfo = error.userInfo[@"NSLocalizedDescription"];
[selfshowHUDMessage:UserInfo? UserInfo:@" Location failed, please try again!"];
}
// The location succeeded
if (regeocode)
{
NSLog(@"reGeocode:%@", regeocode);
if (regeocode)
{
if([ERPAMapLocationTool inChineseMainlandWithCLLocation:location regeocode:regeocode]){
}else{
// If the user is not in the mainland, the user is not allowed to change the location. The message "Your latest location is not supported!" is displayed. .
[self showHUDMessage:@" Your latest location is not supported within the scope!"];
return;
}
NSString *text = [NSString stringWithFormat:@ % @ % @ % @ "",regeocode.street,regeocode.number,regeocode.POIName];
self.address = regeocode.formattedAddress ? regeocode.formattedAddress :@ "";
ProvinceName (string, optional): provinceName, cityName (string, optional): cityName, areaName (string, optional): Longitude1 (String, Endogenous): Longitude2 (string, endogenous): longitude2 (string, endogenous): longitude2 (String, endogenous) Latitude, Nature (integer, optional): specifies the customer type, */
// You need to save the latitude and longitude
NSString* lon = [NSString stringWithFormat:@"%f", location.coordinate.longitude];
NSString* lat = [NSString stringWithFormat:@"%f", location.coordinate.latitude];
// Keep it up. Update the TV
weakSelf.longitude1 = lon;
weakSelf.longitude2 = lat;
[_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:1]] withRowAnimation:UITableViewRowAnimationNone]; [weakSelf setupk_API_Account_Merchant_UpdateMerchantGeo]; }}}];Copy the code
- The realization of the SingleLocation
- (void)SingleLocation:(AMapLocatingCompletionBlock)completionBlock{
// First determine the status, such as whether to authorize
self.location = [[AMapLocationManager alloc]init];
// Determine whether the user has authorized the application to obtain location permission
// iOS developer detects whether location is enabled: showAlert
if(! [QCTSession isHasLocationAuthorityWithisShowAlert:YES]) {
return;
}
/ / [[QCT_Common getCurrentVC] showHUDProgressWithMessage: @ "positioning of..." style: MBPHUDProgressStyleAnnular];
[[QCT_Common getCurrentVC] showHUDProgressWithMessage:@" Positioning..." style:MBPHUDProgressStyleNormal];
[self.location setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
// Set the minimum timeout period to 2 seconds
self.location.locationTimeout = 2;
// Set the timeout period for the reverse geographical request to 2s
self.location.reGeocodeTimeout = 2;
/ / [self showHUDProgressWithMessage: @ "positioning of..." style: MBPHUDProgressStyleAnnular];
[self.location requestLocationWithReGeocode:YES completionBlock:completionBlock];
// [self hideHUD];
}
Copy the code
- Processing for kCLAuthorizationStatusNotDetermined [[AMapLocationKit] to use in iOS version 11 or more background location services, Need to implement amapLocationManager: doRequireLocationAuth: agency problems and solution method 】
/** 1, limit foreign location (optimized location permission check logic: mainly for iOS13 access location information added [next ask] scenario) : iOS13 added App location access "only allowed once" 1.1) : test method: First set [allow when using app], and then go to the system Settings to modify the location information permission to: [ask next time]. Go back to the app and update your location information. Before positioning testing authority, if it is kCLAuthorizationStatusNotDetermined, need to implement this method, to let users to choose. KCLAuthorizationStatusNotDetermined / / users do not have to choose whether you want to use location services (play box have no choice, or no bullet box) * /
- (void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager*)locationManager
{
[locationManager requestAlwaysAuthorization];
}
Copy the code
- Monitoring location status
- (void)amapLocationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
switch (status) {
case kCLAuthorizationStatusNotDetermined:
break;
case kCLAuthorizationStatusDenied:
{
[QCTSession setupkCLAuthorizationStatusDenied];
}
break;
default:
break;
}
// [[QCT_Common getCurrentVC] hideHUD];
}
Copy the code
- Modify location did not open the clues setupkCLAuthorizationStatusDenied
+ (void)setupkCLAuthorizationStatusDenied{
// [[QCT_Common getCurrentVC] hideHUD];
[LBAlertController showAlertTitle:@" Location service not enabled" content:@" Please enter the system "Settings" "Privacy" "location services" \" turn on the switch, and allow the use of location services" cancelString:@ "cancel" cancleBlock:nil sureString:@" Open now" sureBlock:^{
// We need to add URL types in info.plist and set URL Schemes to prefs
if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString[[]]) {UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
} currentController:[QCT_Common getCurrentVC]];
return;
[LBAlertController showAlertTitle:@" Unable to use location" content:@" Please allow access to your geographical location in the \" Settings - Privacy - Location \" on your iPhone." cancelString:@ "cancel" cancleBlock:nil sureString:@" Go set" sureBlock:^{
// We need to add URL types in info.plist and set URL Schemes to prefs
if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString[[]]) {UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
} currentController:[QCT_Common getCurrentVC]];
}
Copy the code
2.2 Permission Judgment: Determines whether the user authorizes the application to obtain the location permission
- Method of use
if(! [QCTSession isHasLocationAuthorityWithisShowAlert:YES]) {
return;
}
Copy the code
- isHasLocationAuthorityWithisShowAlert
//iOS Jump System Settings to open the location page+ (BOOL)isHasLocationAuthorityWithisShowAlert:(BOOL)showAlert{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
// The location permission of the application is restricted
// Refuse to get the location
if (status == kCLAuthorizationStatusRestricted || status == kCLAuthorizationStatusDenied) {
NSLog(At sign, "NSLog does not have access to geolocation.");
if (showAlert) {
[LBAlertController showAlertTitle:@" Unable to use location" content:@" Please allow access to your geographical location in the \" Settings - Privacy - Location \" on your iPhone." cancelString:@ "cancel" cancleBlock:nil sureString:@" Go set" sureBlock:^{
// We need to add URL types in info.plist and set URL Schemes to prefs
if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString[[]]) {UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
} currentController:[QCT_Common getCurrentVC]];
}
return NO;
}else if (status == kCLAuthorizationStatusNotDetermined){// The user has not yet selected the application, if using the Autonavi SDK location can not execute. As long as the implementation amapLocationManager: doRequireLocationAuth: proxy method
CLLocationManager *manager = [[CLLocationManager alloc] init];
if([manager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
[manager requestWhenInUseAuthorization];
};
}
NSLog(@" Obtaining location permission normal ==============");
return YES;
}
Copy the code
2.3 Handling [Allow Positioning Permission Popup in Non-First Installation]
- AppDelegate detects location permissions
Open the app prompt positioning permission pop-up, for iOS13 every time to ask the next time, for user experience to remove
{CLLocationManager *locationManager; } * /
- (void) setupgetUserLocationAuth{
NSLog(@"setupgetUserLocationAuth: Location permission popup for non-first installation");
if(! [self getUserLocationAuth]) {// Allow access
locationManager = [[CLLocationManager alloc] init];
[locationManager requestAlwaysAuthorization];
/ / create a CLLocationManager object, before using location service call requestWhenInUseAuthorization (). prompt[locationManager requestWhenInUseAuthorization]; }} - (BOOL)getUserLocationAuth {
BOOL result = NO;
switch ([CLLocationManager authorizationStatus]) {
case kCLAuthorizationStatusNotDetermined:
break;
case kCLAuthorizationStatusRestricted:
break;
case kCLAuthorizationStatusDenied:
break;
case kCLAuthorizationStatusAuthorizedAlways:
result = YES;
break;
case kCLAuthorizationStatusAuthorizedWhenInUse:
result = YES;
break;
default:
break;
}
return result;
}
Copy the code
III. Determine whether the new location address is within the mainland
To determine whether a target longitude and latitude in the mainland kunnan.blog.csdn.net/article/det…
Judge by latitude and longitude. Use Autonavi SDK for judgment. (Reverse geocoding for latitude and longitude if you enter the location manually)
see also
Official account: iOS reverse