我做了一个小逻辑来为每个活动获取最佳折线并优化绘制,因为我们需要一定数量的纬度和经度才能绘制出用户制作的最佳轨迹。
假设当用户按下开始一个新活动时,它会提示 3 个选项,跑步、步行或骑自行车。
此方法获取用户选择的内容,并为每个更新 locationRequest。
public void setTrackActivity(long interval, long fastInterval) {
//Update the locationRequest intervals for each different Activity
mLocationRequest.setInterval(interval);
mLocationRequest.setFastestInterval(fastInterval);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
- 对于步行,我将 locationRequest 间隔设置在 6 秒内
每个请求的延迟。
- 为了运行,我将 locationRequest 间隔设置在 2 秒延迟内
每个请求。
- 为了运行,我将 locationRequest 间隔设置在 1 秒延迟内
每个请求。
然后,为了在绘制地图时节省更多的折线,我采用了相同的概念。如果用户正在走路,它会在每 30 条折线中追踪一条折线
public void drawTrack(GoogleMap googleMap) {
googleMap.clear(); //Clearing markers and polylines
PolylineOptions polyline_options = new PolylineOptions().addAll(mLinkedList)
.color(ContextCompat.getColor(mContext, R.color.colorAccent)).width(Constants.POLYLINE_WIDTH).geodesic(true);
// Adding the polyline to the map
Polyline polyline = googleMap.addPolyline(polyline_options);
// set the zindex so that the poly line stays on top of my tile overlays
polyline.setZIndex(1000);
// we add each polyline to an array of polylines
mPolylinesArray.add(polyline);
// We add the latest latlang points we got
mLatLngArray.add(mLinkedList.getLast());
//If we have made 30 polylines we store 1 line starting from that first point to the last, so we can save 28 polylines and draw one instead of having so many points for lets say 10 meters, this value must change depending on the activity, if biking, runing or walking
if (mLatLngArray.size() % 30 == 0) {
// First we delete all polylines saved at the array
for (Polyline pline : mPolylinesArray) {
pline.remove();
}
// We create a new polyline based on the first and last latlang from the 30 we took
Polyline routeSoFar = googleMap.addPolyline(new PolylineOptions().color(Color.GREEN).width(Constants.POLYLINE_WIDTH).geodesic(true));
// Draw the polyline
routeSoFar.setPoints(mLatLngArray);
// set the zindex so that the poly line stays on top of my tile overlays
routeSoFar.setZIndex(1000);
// Clear polyline array
mPolylinesArray.clear();
// Add polyline to array
mPolylinesArray.add(routeSoFar);
}
}
其中mLinkedList 是LinkedList<LatLng>,因此我们可以拥有第一个和最后一个元素(如果您想在活动开始和活动结束时绘制自定义标记)
mPolylinesArray 是Polylines ArrayList<Polyline> 的数组