In the Add HMS API scenario, please refer to all sections to complete the conversion.
In the To HMS API scenario, you only need to refer to sections 1.1 Preparations, 1.2 gradle File Configuration and 7 setMapStyle(). If discarded APIs are used, please also refer to 6. Substitute Solutions for Certain Discarded APIs.
After the conversion is complete, synchronize the project, reload the dependencies, and ensure that the new dependencies are downloaded.
If you want your app to support HMS Map Kit, complete the following steps described in Preparations:
Configuring App Information in AppGallery Connect
Integrating the HMS SDK
Configuring Obfuscation Scripts
Applying for Permissions
If you want your app to support Map.getMylocaiton(), Map.setOnMyLocationChangeListener(), and other methods that are not recommended, you can use the corresponding methods of HUAWEI Location Kit instead. Please refer to the References of HUAWEI Location Kit and the sample code in 6. Substitute Solutions for Certain Discarded APIs.
In the Add HMS API or To HMS API scenario, ensure that minSdkVerison is 19 or later, targetSdkVerison is 29 or later, compileSdkVersion is 29 or later, and buildTooslVerison is '29.0.2' or later at the defaultConfig{} configuration in the gradle file of module.
- compileSdkVersion 29
- buildToolsVersion '29.0.2'
- defaultConfig {
- minSdkVersion 19
- targetSdkVersion 29
- }
Add the androidx.appcompat:appcompat dependency to the gradle file in module.
- implementation 'androidx.appcompat:appcompat:1.1.0'
- implementation 'androidx.recyclerview:recyclerview:1.1.0'
Ensure that the AppCompatActivity inherited by Activity for initially instantiating SupportMapFragment is in the adnroidx.appcompat:appcompat package.
- public class CameraDemoActivity extends androidx.appcompat.app.AppCompatActivity
In the Add HMS API scenario, the Google base and basement plug-in version added in the gradle file in module must be 17.1.0 or later.
- implementation 'com.google.android.gms:play-services-base:17.1.0'
- implementation 'com.google.android.gms:play-services-basement:17.1.0'
Add the JDK 1.8 display dependency.
- compileOptions {sourceCompatibility = 1.8 targetCompatibility = 1.8}
After the conversion is complete, case expressions must be constant expression is displayed for some statements selected using switch-case. The case in switch must be an exception expressed in a constant. This method needs to be converted to the if-else format to resolve the switch exception.
Original sample code:
- switch (reason) {
- case OnCameraMoveStartedListener.REASON_GESTURE:
- currPolylineOptions.color(Color.BLUE);
- reasonText = "GESTURE";
- break;
- case OnCameraMoveStartedListener.REASON_API_ANIMATION:
- currPolylineOptions.color(Color.RED);
- reasonText = "API_ANIMATION";
- break;
- case OnCameraMoveStartedListener.REASON_DEVELOPER_ANIMATION:
- currPolylineOptions.color(Color.GREEN);
- reasonText = "DEVELOPER_ANIMATION";
- break;
- }
Modified sample code:
- if (OnCameraMoveStartedListener.getREASON_GESTURE() == reason) {
- this.currPolylineOptions.color(Color.BLUE);
- reasonText = "GESTURE";
- } else if (OnCameraMoveStartedListener.getREASON_API_ANIMATION() == reason) {
- this.currPolylineOptions.color(Color.RED);
- reasonText = "API_ANIMATION";
- } else if (OnCameraMoveStartedListener.getREASON_DEVELOPER_ANIMATION() == reason) {
- this.currPolylineOptions.color(Color.GREEN);
- reasonText = "DEVELOPER_ANIMATION";
- } else {
- reasonText = "UNKNOWN_REASON";
- }
After the Add HMS API conversion is complete, you can configure the classloader (simple, only resource import and configuration file modification are required) or manually write code (complex, heavy manual conversion workload) to implement the compatibility of Google APIs and HMS for activity displayed in fragment.
Currently, the classloader mode does not support Add HMS API conversion in Generate code for creating app dependent only on GMS SDK mode. Do not select it when using the tool for conversion.

1. Decompress the package and cut the resource files.
a. Decompress the fragment-support.zip package in the project-level directory xmsadapter/src/main/java.
b. Move the scripts, src, xh, and xg folders to the xmsadapter folder.
2. Modify the project-related configuration files.
a. Add the following reference to the settings.gradle file in the project-level directory:
- include ':xmsadapter:xh', ':xmsadapter:xg'
b. In the dependencies {} area of the build.gradle file in the project-level directory, set the Gradle plug-in version to 3.5.0 or later.
- buildscript {
- dependencies {
- classpath 'com.android.tools.build:gradle:3.5.0'
- }
- }
c. In the gradle/wrapper/gradle-wrapper.properties file in the project-level directory, set the Gradle version to 5.4.1 or later.
- distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
d. In the build.gradle file in the app-level directory, set minSdkVersion to 24 or later and add the following dependency in the dependencies {} area:
- android {
- defaultConfig {
- minSdkVersion 24
- }
- }
- dependencies {
- compileOnly project(':xmsadapter:xh')
- compileOnly project(':xmsadapter:xg')
- }
e. Add the following reference to the xmsadapter/build.gradle file in the project-level directory:
- apply from: 'scripts/copy-dex.gradle'
3. Change the fragment-related package names.
In Android Studio, choose Edit > Find > Replace in Path, select the Module and app filters (as shown in the red boxes in the following figure), replace com.google.android.gms.maps with org.xms.g.maps, and click Replace All.

4. Call the init method at the program entry to initialize the program.
a. Implement a program entry class that inherits android.app.Application in the app and overwrite the onCreate method in the class.
- public class MyApp extends Application {
- @Override
- public void onCreate() {
- super.onCreate();
- GlobalEnvSetting.init(this,null);
- XMS.init(this);
- }
- }
b. Modify the application name attribute in the src/main/AndroidManifest.xml file in the app-level directory and add the new application subclass in the first entry.
- <application
- android:name=".MyApp"
- </application>
5.Configure the obfuscation rule for the packaged app version for release.
a.If the obfuscation optimization parameter of the proguard tool is enabled when your app is packaged into a version for release, check whether thebuild.gradlefile of the app contains the following content. If yes, the obfuscation optimization parameter is enabled. In this case, go to step b. Otherwise, skip this step.
- android {
- buildTypes {
- release {
- minifyEnabled true
- proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
- }
- }
- }
b.To prevent the proguard tool from incorrectly obfuscating or removing fragment-related code, configure the following obfuscation filtering rules in theproguard-rules.profile in the app-level directory:
- -keep class * extends androidx.fragment.app.Fragment{*;}
- -keep class org.xms.g.maps.ExtensionMapOptions{*;}
- -keep class com.huawei.hms.maps.HuaweiMapOptions{*;}
- -keep class com.google.android.gms.maps.GoogleMapOptions{*;}
- -keep interface org.xms.g.maps.OnMapReadyCallback{*;}
- -keep interface com.huawei.hms.maps.OnMapReadyCallback{*;}
- -keep interface com.google.android.gms.maps.OnMapReadyCallback{*;}
- -keep class org.xms.g.maps.StreetViewPanoramaOptions{*;}
- -keep class com.google.android.gms.maps.OnStreetViewPanoramaReadyCallback{*;}
- -keep class com.huawei.hms.maps.OnStreetViewPanoramaReadyCallback{*;}
- -keep interface org.xms.g.maps.OnStreetViewPanoramaReadyCallback{*;}
- -keep interface com.google.android.gms.maps.OnStreetViewPanoramaReadyCallback{*;}
- -keep interface com.huawei.hms.maps.OnStreetViewPanoramaReadyCallback{*;}
- -keep class com.huawei.hms.dynamicloader.** { *; }
- -keep class com.huawei.hms.feature.dynamic.** {*;}
- -keep class com.huawei.hms.feature.** { *;}
6.Handle the exception.
It is recommended that you do not rescan a project.
If a rescanning is performed, you will see the message shown in the following figure. In this case, back up and remove the xh and xg folders from the xmsadapter folder. After the rescanning is complete, restore the backup to the xmsadapter folder.

1. Modify the layout resource file.
In the Add HMS API scenario, Google APIs and HMS need to use independent layout resource files. The <fragment/>class paths in the resource files are different.
Reference for the fragment definition in the HMS layout resource file:
- <fragment
- android:id="@+id/map"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- class="com.huawei.hms.maps.SupportMapFragment" />
Reference for the fragment definition in the Google API layout resource file:
- <fragment
- android:id="@+id/map"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- class="com.google.android.gms.maps.SupportMapFragment" />
Resource file reference:
basic_demo: original layout resource file
basic_demo_hms: layout resource file of HMS

Each layout resource file must be in duplicate, one for HMS and the other for Google APIs. The files are used together with the code for compatible redirection.
2. Modify the code.
If fragment is used, you can use if-else in the onCreate() method of activity to make a copy of the code compatible with both HMS and Google APIs. The modification method is as follows:
Original sample code:
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.events_demo);
- mTapTextView = (TextView) findViewById(R.id.tap_text);
- mCameraTextView = (TextView) findViewById(R.id.camera_text);
- SupportMapFragment mapFragment =
- (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
- mapFragment.getMapAsync(this);
- }
Modified sample code:
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- //Create according to G or H based on the current type.
- if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
- createAsH();
- } else {
- createAsG();
- }
- }
- /**
- * HMS creation process
- */
- private void createAsH() {
- Log.d(TAG, "create as hms");
- // Set the HMS resource file.
- setContentView(R.layout.events_demo_hms);
- // Initialize parameters.
- initMember();
- // Obtain the HMS fragment based on the ID.
- com.huawei.hms.maps.SupportMapFragment hMapFragment =
- (com.huawei.hms.maps.SupportMapFragment) this.getSupportFragmentManager().findFragmentById(R.id.map);
- // Load a map.
- hMapFragment.getMapAsync(this.getHInstanceOnMapReadyCallback());
- }
- /**
- * GMS creation process
- */
- private void createAsG() {
- Log.d(TAG, "create as gms");
- // Set the GMS resource file.
- setContentView(R.layout.events_demo);
- // Initialize parameters.
- initMember();
- // Obtain the GMS fragment based on the ID.
- com.google.android.gms.maps.SupportMapFragment gMapFragment =
- (com.google.android.gms.maps.SupportMapFragment) this.getSupportFragmentManager()
- .findFragmentById(R.id.map);
- // Load a map.
- gMapFragment.getMapAsync(this.getGInstanceOnMapReadyCallback());
- }
- /**
- * Initialize member variables and extract them into independent methods.
- */
- private void initMember() {
- this.mTapTextView = (TextView) findViewById(R.id.tap_text);
- this.mCameraTextView = (TextView) findViewById(R.id.camera_text);
- }
Specify Google APIs or HMS to load map resources based on isHms in the current environment variable. The options are as follows:
- void initMember(): initialization position of private member variables and code that can be shared.
- void createAsG(): Google API creation process.
- void createAsH(): HMS creation process.
After the conversion is complete, please refer to the following table if an exception occurs in the reference of constants. In GoogleMap, constants are directly used. However, in the Add HMS API scenario, constants are used in Getter mode. For example:
For BitmapDescriptorFactory.HUE_ORANGE, the new method is to use BitmapDescriptorFactory.getHUE_ORANGE() in Getter mode.
Getting googleMap Constants | Getting Add HMS API Constants |
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_HYBRID. (directly used after reference) | ExtensionMap.getMAP_TYPE_NORMAL() |
BitmapDescriptorFactory.HUE_ORANGE | BitmapDescriptorFactory.getHUE_ORANGE(); |
HuaweiMap.OnCameraMoveStartedListener.REASON_API_ANIMATION | HuaweiMap.OnCameraMoveStartedListener.getREASON_API_ANIMATION() |
Getting googleMap Constants | Getting To HMS API Constants |
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_HYBRID. (directly used after reference) | import static com.huawei.hms.maps.HuaweiMap.MAP_TYPE_HYBRID. (directly used after reference) |
Some demos such as Marker implement the OnMapAndViewReadyListener.OnGlobalLayoutAndMapReadyListener API. The Fragment used supports conversion in the OnMapAndViewReadyListener class in the Add HMS API scenario. The modification is as follows.
l Modify the constructor. The parameter type of the constructor mapFragment needs to be converted from SupportMapFragment to the parent class Fragment.
- public OnMapAndViewReadyListener(
- Fragment mapFragment, OnGlobalLayoutAndMapReadyListener devCallback) {}
l The sample code for OnMapAndViewReadyListener compatible with Google APIs and HMS is as follows:
- public class OnMapAndViewReadyListener implements OnGlobalLayoutListener, OnMapReadyCallback {
- /**
- * A listener that needs to wait for both the GoogleMap and the View to be initialized.
- */
- public interface OnGlobalLayoutAndMapReadyListener {
- void onMapReady(ExtensionMap googleMap);
- }
- private final View mapView;
- private final OnGlobalLayoutAndMapReadyListener devCallback;
- private boolean isViewReady;
- private boolean isMapReady;
- private ExtensionMap googleMap;
- public OnMapAndViewReadyListener(
- Fragment mapFragment, OnGlobalLayoutAndMapReadyListener devCallback) {
- // HMS processing
- if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
- com.huawei.hms.maps.SupportMapFragment hMapFragment = (com.huawei.hms.maps.SupportMapFragment) mapFragment;
- mapView = mapFragment.getView();
- this.devCallback = devCallback;
- registerListeners();
- // GoogleMap. Note if the GoogleMap is already ready it will still fire the callback later.
- hMapFragment.getMapAsync(this.getHInstanceOnMapReadyCallback());
- } else {
- // GMS processing
- com.google.android.gms.maps.SupportMapFragment gMapFragment = (com.google.android.gms.maps.SupportMapFragment) mapFragment;
- mapView = mapFragment.getView();
- this.devCallback = devCallback;
- registerListeners();
- // GoogleMap. Note if the GoogleMap is already ready it will still fire the callback later.
- gMapFragment.getMapAsync(this.getGInstanceOnMapReadyCallback());
- }
- }
- private void registerListeners() {
- isViewReady = false;
- isMapReady = false;
- googleMap = null;
- // View layout.
- if ((mapView.getWidth() != 0) && (mapView.getHeight() != 0)) {
- // View has already completed layout.
- isViewReady = true;
- } else {
- // Map has not undergone layout, register a View observer.
- mapView.getViewTreeObserver().addOnGlobalLayoutListener(this);
- }
- }
- @Override
- public void onMapReady(ExtensionMap googleMap) {
- // NOTE: The GoogleMap API specifies the listener is removed just prior to invocation.
- this.googleMap = googleMap;
- isMapReady = true;
- fireCallbackIfReady();
- }
- @SuppressWarnings("deprecation") // We use the new method when supported
- @SuppressLint("NewApi") // We check which build version we are using.
- @Override
- public void onGlobalLayout() {
- // Remove our listener.
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
- mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
- } else {
- mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
- }
- isViewReady = true;
- fireCallbackIfReady();
- }
- private void fireCallbackIfReady() {
- if (isViewReady && isMapReady) {
- devCallback.onMapReady(googleMap);
- }
- }
- }
l In the Add HMS API scenario, the sample code of onCreate() modification for activity to call OnMapAndViewReadyListener is as follows:
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
- createAsH();
- } else {
- createAsG();
- }
- }
- private void createAsH() {
- Log.d(TAG, "create as hms");
- setContentView(R.layout.marker_demo_hms);
- initMember();
- com.huawei.hms.maps.SupportMapFragment hMapFragment = (com.huawei.hms.maps.SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
- new OnMapAndViewReadyListener(hMapFragment, this);
- }
- private void createAsG() {
- Log.d(TAG, "create as gms");
- setContentView(R.layout.marker_demo);
- initMember();
- com.google.android.gms.maps.SupportMapFragment hMapFragment = (com.google.android.gms.maps.SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
- new OnMapAndViewReadyListener(hMapFragment, this);
- }
- private void initMember() {
- this.mTopText = (TextView) findViewById(R.id.top_text);
- this.mRotationBar = (SeekBar) findViewById(R.id.rotationSeekBar);
- this.mRotationBar.setMax(360);
- this.mRotationBar.setOnSeekBarChangeListener(this);
- this.mFlatBox = (CheckBox) findViewById(R.id.flat);
- this.mOptions = (RadioGroup) findViewById(R.id.custom_info_window_options);
- this.mOptions.setOnCheckedChangeListener(new OnCheckedChangeListener() {
- @Override
- public void onCheckedChanged(RadioGroup group, int checkedId) {
- if (MarkerDemoActivity.this.mLastSelectedMarker != null && MarkerDemoActivity.this.mLastSelectedMarker.isInfoWindowShown()) {
- // Refresh the info window when the info window's content has changed.
- MarkerDemoActivity.this.mLastSelectedMarker.showInfoWindow();
- }
- }
- });
- }
In the Add HMS API scenario, the call method of fragment is slightly different from that of streeViewPanoramaFragment compared with 2. fragment. However, the basic approach is to perform if-else processing based on the system type. The reference is as follows.
l Sample code of modifying onCreate in activity
Original code:
- protected void onCreate(final Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.street_view_panorama_basic_demo);
- SupportStreetViewPanoramaFragment streetViewPanoramaFragment =
- (SupportStreetViewPanoramaFragment)
- getSupportFragmentManager().findFragmentById(R.id.streetviewpanorama);
- streetViewPanoramaFragment.getStreetViewPanoramaAsync(
- new OnStreetViewPanoramaReadyCallback() {
- @Override
- public void onStreetViewPanoramaReady(StreetViewPanorama panorama) {
- // Only set the panorama to SYDNEY on startup (when no panoramas have been
- // loaded which is when the savedInstanceState is null).
- if (savedInstanceState == null) {
- panorama.setPosition(SYDNEY);
- }
- }
- });
- }
Modified sample code:
- @Override
- protected void onCreate(final Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- if (org.xms.g.utils.GlobalEnvSetting.isHms()) {
- createAsH(savedInstanceState);
- } else {
- createAsG(savedInstanceState);
- }
- }
- private void createAsH(final Bundle savedInstanceState) {
- Log.d(TAG, "create as hms");
- setContentView(R.layout.street_view_panorama_basic_demo_hms);
- initMember();
- com.huawei.hms.maps.SupportStreetViewPanoramaFragment hStreetViewPanoramaFragment =
- (com.huawei.hms.maps.SupportStreetViewPanoramaFragment) getSupportFragmentManager().findFragmentById(R.id.streetviewpanorama);
- hStreetViewPanoramaFragment.getStreetViewPanoramaAsync(panorama -> {
- // Only set the panorama to SYDNEY on startup (when no panoramas have been
- // loaded which is when the savedInstanceState is null).
- // Convert to org.xms for HMS.
- org.xms.g.maps.StreetViewPanorama xmsStreetViewPanorama =
- new org.xms.g.maps.StreetViewPanorama(null, panorama);
- if (savedInstanceState == null) {
- xmsStreetViewPanorama.setPosition(SYDNEY);
- }
- });
- }
- private void createAsG(final Bundle savedInstanceState) {
- Log.d(TAG, "create as gms");
- setContentView(R.layout.street_view_panorama_basic_demo);
- initMember();
- com.google.android.gms.maps.SupportStreetViewPanoramaFragment gStreetViewPanoramaFragment =
- (com.google.android.gms.maps.SupportStreetViewPanoramaFragment) getSupportFragmentManager().findFragmentById(R.id.streetviewpanorama);
- gStreetViewPanoramaFragment.getStreetViewPanoramaAsync(panorama -> {
- // Only set the panorama to SYDNEY on startup (when no panoramas have been
- // loaded which is when the savedInstanceState is null).
- // Convert to org.xms for HMS.
- org.xms.g.maps.StreetViewPanorama xmsStreetViewPanorama =
- new org.xms.g.maps.StreetViewPanorama(panorama, null);
- if (savedInstanceState == null) {
- xmsStreetViewPanorama.setPosition(SYDNEY);
- }
- });
- }
- private void initMember() {
- }
For details about how to call streeViewPanoramaFragment, please refer to the sample code to make adjustment.
If Location Kit APIs are used in the To HMS API scenario, the Location dependency needs to be added. For details about the version number in ${version, please refer to Version Change History of Location Kit.
- implementation 'com.huawei.hms:location:${version}'
To use the Location function, ensure that you have obtained the location permission.
Sample code for obtaining the location permission:
- /**
- * only have permission of location, location function is enable
- **/
- if(enableMyLocation()){
- getMyLocation();
- setOnMyLocationChangeListener();
- }
- /**
- * Request code for location permission request.
- *
- * @see #onRequestPermissionsResult(int, String[], int[])
- */
- private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
- /**
- * Enables the My Location layer if the fine location permission has been granted.
- */
- private boolean enableMyLocation() {
- if (ContextCompat.checkSelfPermission(this,
- Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- // Permission to access the location is missing.
- PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
- Manifest.permission.ACCESS_FINE_LOCATION, true);
- return false;
- }else {
- return true;
- }
- }
This API can be replaced by the FusedLocationProviderClient.getLastLocation() method of HUAWEI Location Kit. For details about the API function, please refer to the getLastLocation() method in the References of HUAWEI Location Kit.
To HMS API sample code:
- // Current position.
- private android.location.Location myLocation;
- /**
- * this is an Example:
- * using location kit getLastLocation ,replace HuaweiMap.getMylocation() function
- */
- private void getMyLocation(){
- com.huawei.hmf.tasks.Task<android.location.Location> locationTask = LocationServices
- .getFusedLocationProviderClient(this).getLastLocation();
- locationTask.addOnCompleteListener(param0 -> {
- if (locationTask != null) {
- myLocation = locationTask.getResult();
- double Lat = myLocation.getLatitude();
- double Lng = myLocation.getLongitude();
- Log.d(TAG, " Lat is : " + Lat +", Lng is : "+Lng);
- }
- }).addOnFailureListener(param0 -> Log.d(TAG,"lastLocation is error"));
- }
Add HMS API sample code:
- //current location
- private android.location.Location myLocation;
- /**
- * this is an Example:
- * using location kit getLastLocation ,replace HuaweiMap.getMylocation() function
- */
- private void getMyLocation(){
- org.xms.g.tasks.Task<android.location.Location> locationTask = LocationServices
- .getFusedLocationProviderClient(this).getLastLocation();
- locationTask.addOnCompleteListener(param0 -> {
- if (locationTask != null) {
- myLocation = locationTask.getResult();
- double Lat = myLocation.getLatitude();
- double Lng = myLocation.getLongitude();
- Log.d(TAG, " Lat is : " + Lat +", Lng is : "+Lng);
- }
- }).addOnFailureListener(param0 -> Log.d(TAG,"lastLocation is error"));
- }
This API can be replaced by the FusedLocationProviderClient.requestLocationUpdates(LocationRequest request,LocationCallback callback,Looper looper) method of HUAWEI Location Kit. For the API description, please refer to FusedLocationProviderClient.
To HMS API sample code:
- /**
- * this is an Example
- * using location kit requestLocationUpdates(Request,LocationCallback,Looper) ,replace HuaweiMap.setOnMyLocationChangeListener()
- */
- private void setOnMyLocationChangeListener(){
- // When you construct request parameters, please refer to the development guide of the Location Kit.
- com.huawei.hms.location.LocationRequest request = new com.huawei.hms.location.LocationRequest();
- request.setInterval(2000);
- LocationServices
- .getFusedLocationProviderClient(this).requestLocationUpdates(request, new LocationCallback() {
- @Override
- public void onLocationResult( com.huawei.hms.location.LocationResult locationResult) {
- if (locationResult != null) {
- List<Location> locations = locationResult.getLocations();
- if (!locations.isEmpty()) {
- for (Location location : locations) {
- Log.i(TAG,
- "onLocationResult location[Longitude,Latitude,Accuracy]:"
- + location.getLongitude() + "," + location.getLatitude() + ","
- + location.getAccuracy());
- }
- }
- }
- }
- @Override
- public void onLocationAvailability(LocationAvailability locationAvailability) {
- if (locationAvailability != null) {
- boolean flag = locationAvailability.isLocationAvailable();
- Log.i(TAG, "onLocationAvailability isLocationAvailable:" + flag);
- }
- }
- }, android.os.Looper.myLooper()).addOnSuccessListener(new OnSuccessListener<Void>() {
- @Override
- public void onSuccess(Void param0) {
- Log.d(TAG,"onSuccess.....");
- }
- });
- }
Add HMS API sample code:
- /**
- * this is an Example
- * using location kit requestLocationUpdates(Request,LocationCallback,Looper) ,replace HuaweiMap.setOnMyLocationChangeListener()
- */
- private void setOnMyLocationChangeListener(){
- // When you construct request parameters, please refer to the development guide of the Location Kit.
- org.xms.g.location.LocationRequest request = new org.xms.g.location.LocationRequest();
- request.setInterval(2000);
- LocationServices
- .getFusedLocationProviderClient(this).requestLocationUpdates(request, new LocationCallback() {
- @Override
- public void onLocationResult( org.xms.g.location.LocationResult locationResult) {
- if (locationResult != null) {
- List<Location> locations = locationResult.getLocations();
- if (!locations.isEmpty()) {
- for (Location location : locations) {
- Log.i(TAG,
- "onLocationResult location[Longitude,Latitude,Accuracy]:"
- + location.getLongitude() + "," + location.getLatitude() + ","
- + location.getAccuracy());
- }
- }
- }
- }
- @Override
- public void onLocationAvailability(LocationAvailability locationAvailability) {
- if (locationAvailability != null) {
- boolean flag = locationAvailability.isLocationAvailable();
- Log.i(TAG, "onLocationAvailability isLocationAvailable:" + flag);
- }
- }
- }, android.os.Looper.myLooper()).addOnSuccessListener(new OnSuccessListener<Void>() {
- @Override
- public void onSuccess(Void param0) {
- Log.d(TAG,"onSuccess.....");
- }
- });
- }
This method can be replaced by the setOnCameraMoveStartedListener, setOnCameraMoveListener, and setOnCameraIdleListener methods for listening to the moveCamera event.
Sample code:
- /**
- * this is an Example
- * using setOnCameraMoveStartedListener, setOnCameraMoveListener, setOnCameraIdleListener to
- * replace to HuaweiMap.setOnCameraChangeListener.
- */
- private void setOnCameraChangeListener() {
- Log.d(TAG, " start addMoveListener...");
- this.mMap.setOnCameraMoveStartedListener(i -> Log.d(TAG," start camera move..."));
- this.mMap.setOnCameraMoveListener(() -> Log.d(TAG," camera moving..."));
- this.mMap.setOnCameraIdleListener(() -> {
- Log.d(TAG," idle camera move... ");
- });
- }
JSON resource files need to be loaded for map style settings (options: retro, night, grayscale, and simple). The JSON file format used by HuaweiMap is different from that used by GoogleMap. As a result, they cannot share the same JSON resource files. Compatibility adaptation is required at the service code layer. To download the map style JSON files for HuaweiMap, please go to Download link.
In the To HMS API scenario, perform the following steps for modification:
1. Download the Huawei JSON files.
2. In the res/raw directory of the project (that is, the directory of the map style JSON resource files, which may vary according to projects), replace the resource files with those of the same names. The following figure shows the files for replacement.

In the Add HMS API scenario, perform the following steps for modification:
1. Download the Huawei JSON files.
2. Add mapstyle_grayscale_hms.json, mapstyle_night_hms.json, and mapstyle_retro_hms.json to the res/raw directory of the project (the directory may vary according to projects) as the map style resource files of HuaweiMap. These files coexist with the map style resource files of GoogleMap. The following figure shows the files after the addition.

3. The following is the sample code for Add HMS API compatibility after the modification: Load different JSON resource files based on system settings.
- private void setSelectedStyle() {
- MapStyleOptions style;
- switch (this.mSelectedStyleId) {
- case R.string.style_label_retro:
- // Sets the retro style via raw resource JSON.
- if(GlobalEnvSetting.isHms()){
- style = MapStyleOptions.loadRawResourceStyle(this, R.raw.mapstyle_retro_hms);
- }else{
- style = MapStyleOptions.loadRawResourceStyle(this, R.raw.mapstyle_retro);
- }
- break;
- case R.string.style_label_night:
- // Sets the night style via raw resource JSON.
- if(GlobalEnvSetting.isHms()){
- style = MapStyleOptions.loadRawResourceStyle(this, R.raw.mapstyle_night_hms);
- }else{
- style = MapStyleOptions.loadRawResourceStyle(this, R.raw.mapstyle_night);
- }
- break;
- case R.string.style_label_grayscale:
- // Sets the grayscale style via raw resource JSON.
- if(GlobalEnvSetting.isHms()){
- style = MapStyleOptions.loadRawResourceStyle(this, R.raw.mapstyle_grayscale_hms);
- }else{
- style = MapStyleOptions.loadRawResourceStyle(this, R.raw.mapstyle_grayscale);
- }
- break;
- case R.string.style_label_no_pois_no_transit:
- // Sets the no POIs or transit style via JSON string.
- style = new MapStyleOptions("[" + " {" + " \"featureType\":\"poi.business\","
- + " \"elementType\":\"all\"," + " \"stylers\":[" + " {"
- + " \"visibility\":\"off\"" + " }" + " ]" + " }," + " {"
- + " \"featureType\":\"transit\"," + " \"elementType\":\"all\"," + " \"stylers\":["
- + " {" + " \"visibility\":\"off\"" + " }" + " ]" + " }" + "]");
- break;
- case R.string.style_label_default:
- // Removes previously set style, by setting it to null.
- style = null;
- break;
- default:
- return;
- }
- this.mMap.setMapStyle(style);
- }