Real-time positioning has become one of the essential capabilities of applications, especially navigation applications, which need to quickly and accurately locate the real-time location of users.

Huawei location services enable applications to quickly and accurately obtain user location information. Meanwhile, location services help global developers to realize personalized map presentation and interaction, and comprehensively improve the LBS experience of applications.

The following describes how huawei location services and map services enable real-time application location.

Expected function

Get real-time positioning, and display the position point on the map, jump to the current position point for the first time, and change the position of the current position point and the view of the map will change.

Using ability

Huawei Location services: Basic location

Huawei Map service: Map display

Realize the principle of

Use Huawei Location services to obtain the real-time location. The My Location button is displayed on the map. When the location changes, the map jumps to the current location.

The preparatory work

AGC account registration, project creation

1. Register as a developer

Registered Address:

Developer.huawei.com/consumer/cn…

2. Create an application, add SHA256, enable map/site, and download the JSON file

Developer.huawei.com/consumer/cn…

3. Configure the Android Studio project

  1. Copy the agconnect-services.json file to the application-level root directory

· In AllProjects > Repositories, configure the Maven repository address for the HMS Core SDK.

· Configure the Maven repository address for the HMS Core SDK in “BuildScript > Repositories”.

· If the “agconnect-services.json” file is added to the App, add the AGCP configuration in “BuildScript > Dependencies”.

buildscript { repositories { maven { url 'https://developer.huawei.com/repo/' } google() jcenter() } dependencies { The classpath 'com. Android. Tools. Build: gradle: 3.3.2 rainfall distribution on 10-12' classpath 'com. Huawei. Agconnect: agcp: 1.3.1.300' allprojects {}} repositories { maven { url 'https://developer.huawei.com/repo/' } google() jcenter() } }Copy the code
  1. In Dependencies, add the following compilation dependencies

    dependencies { implementation ‘com.huawei.hms:maps:{version}’ implementation ‘com.huawei.hms:location:{version}’ }

  2. Add the configuration in the file header

    apply plugin: ‘com.huawei.agconnect’

  3. Configure the signature on Android. Copy the signature file generated by the signature certificate fingerprint to the app directory of your project, and configure the signature in the “build.gradle” file

    SigningConfigs {release {// signed certificate storeFile file(“.”) // keystore password storePassword “” // alias keyAlias “” // keyPassword keyPassword “******” v2SigningEnabled true v2SigningEnabled true } }

    buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile(‘proguard-android.txt’), ‘proguard-rules.pro’ debuggable true } debug { debuggable true } }

Key code implementation

  1. Write a service to get real-time location.

    public class LocationService extends Service {

    private final String TAG = this.getClass().getSimpleName(); List<ILocationChangedLister> locationChangedList = new ArrayList<>(); // location private FusedLocationProviderClient fusedLocationProviderClient; private LocationRequest mLocationRequest; private final LocationCallback mLocationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { super.onLocationResult(locationResult); locationResult.getLocations(); Log.d(TAG, "onLocationResult: " + locationResult); Location location = locationResult.getLocations().get(0); Log.w(TAG, "onLocationResult:Latitude " + location.getLatitude()); Log.w(TAG, "onLocationResult:Longitude " + location.getLongitude()); for (ILocationChangedLister locationChanged : locationChangedList) { locationChanged.locationChanged(new LatLng(location.getLatitude(), location.getLongitude())); } } @Override public void onLocationAvailability(LocationAvailability locationAvailability) { super.onLocationAvailability(locationAvailability); Log.d(TAG, "onLocationAvailability: " + locationAvailability.toString()); }}; private final MyBinder binder = new MyBinder(); private final Random generator = new Random(); @Nullable @Override public IBinder onBind(Intent intent) { return binder; } @Override public void onCreate() { Log.i("DemoLog", "TestService -> onCreate, Thread: " + Thread.currentThread().getName()); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("DemoLog", "TestService -> onStartCommand, startId: " + startId + ", Thread: " + Thread.currentThread().getName()); return START_NOT_STICKY; } @Override public boolean onUnbind(Intent intent) { Log.i("DemoLog", "TestService -> onUnbind, from:" + intent.getStringExtra("from")); return false; } @Override public void onDestroy() { Log.i("DemoLog", "TestService -> onDestroy, Thread: " + Thread.currentThread().getName()); super.onDestroy(); } public int getRandomNumber() { return generator.nextInt(); } public void addLocationChangedlister(ILocationChangedLister iLocationChangedLister) { locationChangedList.add(iLocationChangedLister); } public void getMyLoction() { Log.d(TAG, "getMyLoction: "); fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); SettingsClient settingsClient = LocationServices.getSettingsClient(this); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); mLocationRequest = new LocationRequest(); builder.addLocationRequest(mLocationRequest); LocationSettingsRequest locationSettingsRequest = builder.build(); // location setting settingsClient.checkLocationSettings(locationSettingsRequest) .addOnSuccessListener(locationSettingsResponse -> fusedLocationProviderClient .requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper()) .addOnSuccessListener(aVoid -> Log.d(TAG, "onSuccess: " + aVoid))) .addOnFailureListener(Throwable::printStackTrace); } public class MyBinder extends Binder { public LocationService getService() { return LocationService.this; } } public interface ILocationChangedLister { /** * Update the location information * * @param latLng The new location information */ public void locationChanged(LatLng latLng); }Copy the code

    }

  2. Draw a map in the Activity and listen for the real-time location

Add map to Xml:

<com.huawei.hms.maps.MapView
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
Copy the code

Activity Map drawing:

mapView.onCreate(null);
mapView.getMapAsync(this);
Copy the code

Drawing is to turn on my position button display

@Override
public void onMapReady(HuaweiMap huaweiMap) {
    hMap = huaweiMap;
    hMap.setMyLocationEnabled(true);
}
Copy the code

Example Set the location service binding listening

private ServiceConnection conn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        isBound = true;
        if (binder instanceof LocationService.MyBinder) {
            LocationService.MyBinder myBinder = (LocationService.MyBinder) binder;
            locationService = myBinder.getService();
            Log.i(TAG, "ActivityA onServiceConnected");
            locationService.addLocationChangedlister(iLocationChangedLister);
            locationService.getMyLoction();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        isBound = false;
        locationService = null;
        Log.i(TAG, "ActivityA onServiceDisconnected");
    }
};
Copy the code

Bind to LocationService:

private void bindLocationService() {
    Intent intent = new Intent(mActivity, LocationService.class);
    intent.putExtra("from", "ActivityA");
    Log.i(TAG, "-------------------------------------------------------------");
    Log.i(TAG, "bindService to ActivityA");
    mActivity.bindService(intent, conn, Context.BIND_AUTO_CREATE);
}
Copy the code

Handle position changes in position change listen

LocationService.ILocationChangedLister iLocationChangedLister = new LocationService.ILocationChangedLister() {
    @Override
    public void locationChanged(LatLng latLng) {
        Log.d(TAG, "locationChanged: " + latLng.latitude);
        Log.d(TAG, "locationChanged: " + latLng.longitude);
        updateLocation(latLng);
    }
};
Copy the code

Updated map latitude and longitude view

private void updateLocation(LatLng latLng) {
    mLatLng = latLng;
    hMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 1));
}
Copy the code

test

Change the simulated position using the simulated position software, the map view and my position button can jump with it. Function realization.

For more information about HMS Core, see: >> Huawei Developer Alliance official website

>> To get the development guide >> to participate in the developer discussion, visit the CSDN community or Reddit community >> To download the demo and sample code, visit Github or Gitee >> To resolve integration issues, visit Stack Overflow

The original link: developer.huawei.com/consumer/cn…

Original author: HMS Core official account