HMS core location service can automatically fill in the receiving address in the life service app

Time:2022-7-2

In apps and applets involving group purchase, takeout, express delivery, housekeeping, logistics, moving and other life services, filling in the receiving address is a function that users use frequently. This function usually adopts a solution that allows users to fill in manually, such as pulling up and down to select Zhejiang Province — > Hangzhou — > Xihu District — > Xixi street, and then switching to the name input box to enter a name — > phone input box to enter a phone and a series of operations. It is not difficult for us to find that entering the address manually is not only time-consuming and laborious, but also there will be the phenomenon of selecting the wrong address accidentally.

Is there any way to help users fill in the address quickly and accurately? With HMS coreLocation servicesWith the ability of integrated positioning + geocoding, life service apps can automatically locate and obtain the current location information of users or the administrative division information and street information of a place, and accurately fill in the address bar. The user does not need to input manually, which reduces the operation time and does not need to worry about filling in the wrong address. The following is the sample code we provide. Developers can easily experience this function by trying it step by step~

Effect display

Development practice

Development steps

I Development preparation

1. Log in to appgallery connect website and click “my project”. Find your project, turn on the location switch in API management, and click the application that needs to configure the signature certificate fingerprint in the project. In the “application” area of the “Project Settings > General” page, click “add certificate fingerprint” after “sha256 certificate fingerprint”, and enter the generated sha256 fingerprint.

2. In the “application” area of the “Project Settings > General” page, click “agconnect services.json” to download the configuration file. Copy the “agconnect services. JSON” file to the application level root directory.

3. Project level “build.gradle” file

buildscript {
    repositories {
        google()
        jcenter()
        maven { url 'https://developer.huawei.com/repo/' }
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.2'
        classpath 'com.huawei.agconnect:agcp:1.6.0.300'
    }
}

allprojects {
    repositories {
        maven { url 'https://developer.huawei.com/repo/' }
        google()
        jcenter()
        mavenCentral()
    }
}

Application level “build.gradle” file

plugins {
    id 'com.android.application'
    id 'com.huawei.agconnect'
}

Add the following compilation dependencies to “dependencies”

implementation 'com.huawei.hms:location:6.3.0.300'

II Permission check

1. Configure the permission access in the “androidmanifest.xml” file_ COARSE_ Location (rough location permission), access_ FINE_ Location (precise location permission) and access_ BACKGROUND_ Location permission

2. Dynamically apply for permission related to positioning (dangerous permission requirements for Android 6.0 and above)

Log.i(TAG, "android sdk < 28 Q");
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        String[] strings =
                {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
        ActivityCompat.requestPermissions(this, strings, 1);
    }
} else {
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
            "android.permission.ACCESS_BACKGROUND_LOCATION") != PackageManager.PERMISSION_GRANTED) {
        String[] strings = {Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                "android.permission.ACCESS_BACKGROUND_LOCATION"};
        ActivityCompat.requestPermissions(this, strings, 2);
    }
}

III Get positioning results

1. Set positioning parameters, including location update interval, positioning type, etc

mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
mSettingsClient = LocationServices.getSettingsClient(this);
mLocationRequest = new LocationRequest();
// Sets the interval for location update (unit: Millisecond)
mLocationRequest.setInterval(5000);
// Sets the priority
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

2. Call the getsettingsclient() interface to get the settingsclient instance. Call checklocationsettings() to check the device switch settings

LocationSettingsRequest locationSettingsRequest = builder.build();
// Before requesting location update, invoke checkLocationSettings to check device settings.
Task locationSettingsResponseTask =
        mSettingsClient.checkLocationSettings(locationSettingsRequest);
				```
				
After checking that the switch is on, call requestlocationupdates() to locate it

locationSettingsResponseTask.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
Log.i(TAG, “check location settings success”);
mFusedLocationProviderClient
.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())
.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Void aVoid) {
Log.i(TAG, “requestLocationUpdatesWithCallback onSuccess”);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e(TAG, “requestLocationUpdatesWithCallback onFailure:” + e.getMessage());
}
});
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e(TAG, “checkLocationSetting onFailure:” + e.getMessage());
int statusCode = 0;
if (e instanceof ApiException) {
statusCode = ((ApiException) e).getStatusCode();
}
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// When the startResolutionForResult is invoked, a dialog box is displayed, asking you
// to open the corresponding permission.
if (e instanceof ResolvableApiException) {
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(MainActivity.this, 0);
}
} catch (IntentSender.SendIntentException sie) {
Log.e(TAG, “PendingIntent unable to execute request.”);
}
break;
default:
break;
}
}
});

###IV 	 Reverse geocoding to obtain the current location

After successfully obtaining the longitude and latitude of the positioning information, pass the longitude and latitude information to the geocoderservice to obtain the geocoding request object, then call the request inverse geocoding method (getfromlocation), set the request (getfromlocationrequest) parameters, and obtain the inverse geocoding information callback.

if (null == mLocationCallback) {
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult != null) {
List locations = locationResult.getLocations();
if (!locations.isEmpty()) {
ExecutorUtil.getInstance().execute(new Runnable() {
@Override
public void run() {
Locale locale = new Locale(“zh”, “CN”);
GeocoderService geocoderService = LocationServices.getGeocoderService(MainActivity.this, locale);
GetFromLocationRequest getFromLocationRequest = new GetFromLocationRequest(locations.get(0).getLatitude(), locations.get(0).getLongitude(), 1);
geocoderService.getFromLocation(getFromLocationRequest)
.addOnSuccessListener(new OnSuccessListener>() {
@Override
public void onSuccess(List hwLocation) {
printGeocoderResult(hwLocation);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.i(TAG, e.getMessage());
}
});
}
});
}
}
}
@Override
public void onLocationAvailability(LocationAvailability locationAvailability) {
if (locationAvailability != null) {
boolean flag = locationAvailability.isLocationAvailable();
Log.i(TAG, “onLocationAvailability isLocationAvailable:” + flag);
}
}
};
}

Finally, the obtained results can be displayed on the interface.



**Learn more > >**

Visit [official website of Huawei developer alliance]( http://developer.huawei.com/consumer/cn/hms?ha_source=hms1 )  
Get [development guidance document]( http://developer.huawei.com/consumer/cn/doc/development?ha_source=hms1 )  
Huawei mobile service open source warehouse address: [github]( http://github.com/HMS-Core )、[Gitee]( http://gitee.com/hms-core )

**Follow us and learn the latest technical information of HMS core at the first time~**