On March 8th, the programmers of Chrysanthemum Factory confessed to the goddess with "trajectory drawing"

In the list of gifts the programmer prepared for his girlfriend, apart from roses, bags, and lipsticks, aren’t there other surprises that are new and intentional?

No! This " × " belongs to Aqiangbi, who is on a business trip in France. As a programmer who has always been low-key, Aqiang decided to give his girlfriend a special little romance on March 8th this year.

On Valentine’s Day just past, the show of affection in the circle of friends is the same . Selina is holding a half-person tall rose, Jessica shows off the newly bought bag, and Rebecca is having dinner with her boyfriend in the candlelight swaying... and Aqiang Geng I want to make a surprise, and give a different confession to the unique Aveline in my heart on Goddess Day.

Looking at the Eiffel Tower outside the window, Ah Qiang was determined to make a living. He used the programmer's ability to eat and wrote a motion trajectory drawing App . In the country of France (fà), he successfully awakened his romantic genes and told his girlfriend with his own actions: Every step I take is like loving you.

124

 

When the March 8th Goddess Festival is approaching, we will provide you with a detailed explanation of this confession tutorial. You may wish to give your goddess a special holiday blessing~

Realization principle

First, use Huawei Location Kit, which uses GNSS, Wi-Fi, base station and other hybrid positioning modes for positioning, which can quickly and accurately obtain location information and achieve global positioning service capabilities; then use Huawei Map Service (Map Kit), Map Kit provides a set of SDK for map development. The map data covers more than 200 countries and regions, supports more than one hundred languages, and uses rich map personalized presentation tools to draw the acquired positioning information on the map. Realize the real-time drawing of the motion trajectory.

It’s a programmer’s romance to confess with trajectory. In addition, the map positioning trajectory drawing function also has rich application scenarios. For example, in sports health applications, it provides LBS capabilities such as recording motion trajectories, replaying motion routes, and calculating motion distances. , Accurately quantify every step of health.

Development preparation

1. Create an application on the Huawei Developer Alliance website and configure the signing certificate
2. Configure the address of the Huawei Maven warehouse, and add the compile SDK dependency in the application-level "build.gradle" file

dependencies {
implementation 'com.huawei.hms:location: 5.1.0.301'
implementation 'com.huawei.hms:maps: 5.1.0.300'
}

3. Configure the obfuscation script. For the
above steps, please refer to the development preparation introduction on the developer website:
https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides/config-agc-0000001057629153?ha_source=hms1
4. Declare system permissions in the AndroidManifest.xml file.
Because Huawei's location service uses multiple hybrid positioning modes such as GNSS, Wi-Fi, and base stations for positioning, it gives your application the ability to quickly and accurately obtain user location information. To the network, precise location permissions, rough location permissions If you need the application to have continuous positioning capabilities when running in the background, you need to apply for the ACCESS_BACKGROUND_LOCATION permission in the Manifest file:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.huawei.hms.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />

Development steps

1. Map presentation

Currently, Huawei Map SDK supports two map containers, SupportMapFragment and MapView. This article uses the SupportMapFragment method.
1) Add a Fragment to the layout file of the Activity (for example: activity_main.xml), and set the attributes of the map through the layout file.

<fragment
    android:id="@+id/mapfragment_routeplanningdemo"
    android:name="com.huawei.hms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

2) To use the map in the application, you need to implement the OnMapReadyCallback interface.

RoutePlanningActivity extends AppCompatActivity implements OnMapReadyCallback

3) Load SupportMapFragment in the onCreate() method of Activity and call getMapAsync() to register the callback.

Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.mapfragment_routeplanningdemo);
if (fragment instanceof SupportMapFragment) {
    SupportMapFragment mSupportMapFragment = (SupportMapFragment) fragment;
    mSupportMapFragment.getMapAsync(this);
}

4) Obtain the HuaweiMap object in the onMapReady callback.

@Override
public void onMapReady(HuaweiMap huaweiMap) {

    hMap = huaweiMap;
    hMap.setMyLocationEnabled(true);
    hMap.getUiSettings().setMyLocationButtonEnabled(true);
}

2. Location function implementation

1) Location permission check

XXPermissions.with(this)
        // 申请多个权限
        .permission(Permission.Group.LOCATION)
        .request(new OnPermission() {
            @Override
            public void hasPermission(List<String> granted, boolean all) {
                if (all) {
                    getMyLoction();
                } else{
                    Toast.makeText(getApplicationContext(),"拒绝权限之后可能会导致功能不能使用",Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void noPermission(List<String> denied, boolean never) {
                if (never) {
                    XXPermissions.startPermissionActivity(RoutePlanningActivity.this, denied);
                } else {
                XXPermissions.startPermissionActivity(RoutePlanningActivity.this, denied);
                }
            }
        });

2) The current location is located and displayed on the map. You need to check whether the positioning switch is turned on first. If it is not turned on, you cannot get the positioning data.

SettingsClient settingsClient = LocationServices.getSettingsClient(this);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
//检查设备定位设置
settingsClient.checkLocationSettings(locationSettingsRequest)
        .addOnSuccessListener(locationSettingsResponse -> {
            //设置满足定位条件,再发起位置请求
            fusedLocationProviderClient
                    .requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())
                    .addOnSuccessListener(aVoid -> {
                        //接口调用成功的处理
                        Log.d(TAG, "onSuccess: " + aVoid);
                    });
        })
        .addOnFailureListener(e -> {
            //设置不满足定位条件
            int statusCode = ((ApiException) e).getStatusCode();
            if (statusCode == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
                try {
                   ResolvableApiException rae = (ResolvableApiException) e;
             //调用startResolutionForResult可以弹窗提示用户打开相应权限
              rae.startResolutionForResult(RoutePlanningActivity.this, 0);
                } catch (IntentSender.SendIntentException sie) {
                    sie.printStackTrace();
                }
            }
        });

3. Draw the line of the route on the map according to the real-time location

private void addPath(LatLng latLng1, LatLng latLng2) {
    PolylineOptions options = new PolylineOptions().color(Color.BLUE).width(5);
    List<LatLng> path = new ArrayList<>();
    path.add(latLng1);
    path.add(latLng2);
    for (LatLng latLng : path) {
        options.add(latLng);
    }
    Polyline polyline = hMap.addPolyline(options);
    mPolylines.add(polyline);
}
在MAP KIT的基础上结合路径规划的能力将定位的结果实时的上传到云测,然后返回路线并展示在地图上。
String mWalkingRoutePlanningURL = "https://mapapi.cloud.huawei.com/mapApi/v1/routeService/walking";
String url = mWalkingRoutePlanningURL + "?key=" + key;

Response response = null;
JSONObject origin = new JSONObject();
JSONObject destination = new JSONObject();
JSONObject json = new JSONObject();
try {
    origin.put("lat", latLng1.latitude);
    origin.put("lng", latLng1.longitude);

    destination.put("lat", latLng2.latitude);
    destination.put("lng", latLng2.longitude);

    json.put("origin", origin);
    json.put("destination", destination);

    RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
    Request request = new Request.Builder().url(url).post(requestBody).build();
    response = getNetClient().initOkHttpClient().newCall(request).execute();
} catch (JSONException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
return response;

Development effect

After the compilation and installation are complete, open the application, and the movement track will be drawn on the map based on the real-time location information

13325346

 

 

>>Visit the official website of Huawei Developer Alliance to learn more about it

>>Get development guidance documents

>>Huawei mobile service open source warehouse address: GitHub , Gitee

Follow us and learn about the latest technical information of Huawei Mobile Services for the first time~

 

Guess you like

Origin blog.csdn.net/HUAWEI_HMSCore/article/details/114407058