In apps and small programs involving group buying, takeaway, express delivery, housekeeping, logistics, moving and other life services, filling in the delivery address is a function frequently used by users. This function usually adopts a solution that allows users to fill in manually, such as pulling up and down to select Zhejiang Province --> Hangzhou City --> Xihu District --> Xixi Street, and then switch to the name input box to enter the name --> phone input box input A series of operations such as telephone calls. From this, it is not difficult to find that manually entering the address is not only time-consuming and labor-intensive, but also accidentally selects the wrong address.
Is there any way to help users fill in the address quickly and accurately? With the integrated positioning + geocoding capabilities of HMS Core positioning services , life service apps can automatically locate and obtain the user's current location information or the administrative division information and street information of a certain place, and accurately fill in the address bar. The user does not need to manually enter it by himself, which reduces the operation time, and no longer has to worry about filling in the wrong address. The following is the sample code we provide, developers can easily experience this function by following the steps to try it~
Show results
development practice
Development steps
1. Preparation for development
1. Log in to the AppGallery Connect website and click "My Projects". Find your project and enable 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 Thumbprint" next to "SHA256 Certificate Thumbprint", and enter the generated SHA256 thumbprint.
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 in "dependencies"
implementation 'com.huawei.hms:location:6.3.0.300'
2. Permission check
1. Configure the permissions ACCESS_COARSE_LOCATION (coarse location permission), ACCESS_FINE_LOCATION (fine location permission) and ACCESS_BACKGROUND_LOCATION permissions in the "AndroidManifest.xml" file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
2. Dynamically apply for location-related permissions (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);
}
}
3. Obtain positioning results
1. Set positioning parameters, including position 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 obtain 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<LocationSettingsResponse> locationSettingsResponseTask =
mSettingsClient.checkLocationSettings(locationSettingsRequest);
After the check switch is turned on, call requestLocationUpdates() to locate
locationSettingsResponseTask.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
Log.i(TAG, "check location settings success");
mFusedLocationProviderClient
.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@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;
}
}
});
4. Reverse geocoding to get the current location
After successfully obtaining the latitude and longitude of the location information, pass the latitude and longitude information to the geocoding request object using the geocoding service (GeocoderService), then call the request inverse geocoding method (getFromLocation), set the request (GetFromLocationRequest) parameters, and get the reverse geocoding information callback .
if (null == mLocationCallback) {
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult != null) {
List<Location> 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<List<HWLocation>>() {
@Override
public void onSuccess(List<HWLocation> 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 details>>
Visit the official website of Huawei Developer Alliance
Get development guidance documents
Huawei Mobile Services Open Source Warehouse Address: GitHub , Gitee
Follow us to know the latest technical information of HMS Core for the first time~
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。