【发布时间】:2018-04-10 22:59:29
【问题描述】:
我实现了一个功能,每秒跟踪用户的位置,并将跟踪的位置添加到折线,绘制用户的路径。问题是我收集的数据和结果线不精确。
下面是我在附近街道上开车时进行的试运行图片的链接。黑线是接收到的数据,注意线是如何零星地从一个点跳到另一个点的。红线大致是折线应该遵循的路径,因为它遵循我在驾驶和跟踪我的 Android 手机中的位置数据时所走的道路。
https://i.imgur.com/9nWEfna.png
下面是与我实现的路径跟踪功能相关的代码。每次按下“跟踪”按钮时,都会创建一条新的折线,并且每秒开始执行一个线程来报告用户的位置。收到后,该位置的纬度将添加到折线中,并重新绘制折线以反映新点的添加。
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
return;
}
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location == null) return;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Current Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15f));
}
});
trackButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
final ArrayList currpath = new ArrayList<LatLng>();
paths.add(currpath);
PolylineOptions currpathlineoptions = new PolylineOptions();
final Polyline currpathline = mMap.addPolyline(currpathlineoptions);
tracking = true;
MapsActivity.this.runOnUiThread(new Runnable() {
@SuppressLint("MissingPermission")
public void run() {
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(MapsActivity.this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location == null) return;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15f));
currpath.add(latLng);
currpathline.setPoints(currpath);
}
});
if(tracking){
Handler h = new Handler();
h.postDelayed(this, 1000);
}
}
});
} else {
tracking = false;
}
}
});
}
}
在处理 Google 地图方面有更多经验的人能否告诉我为什么 LatLngs 报告从一个点跳到另一个点并且不精确地跟踪我驾驶的路线?
【问题讨论】:
-
从图片中可以看出,您在路线过程中有 6 次位置更新。 6 个中有 5 个相对于引用的事实进行了很好的推算。但是第 6 点(序列中的第 4 点)是不准确的。仅仅因为您每秒采样并不意味着每秒都有更新。从您指定的代码中,您不是在请求位置更新,而只是由于其他请求而对位置进行采样。我建议您按照与您的投票一致的时间间隔请求位置更新。
-
您需要使用
requestLocationUpdates()实际请求位置。在此处查看答案中的代码:stackoverflow.com/questions/44992014/…
标签: android google-maps