我正在寻找一种更好的方式在Android上的谷歌地图v2上实时绘制路线。我正在开发android路由跟踪应用程序,所以基本上我有一个连续的服务 跟踪我在后台的位置,并使用地图片段通过广播向我的活动发送位置更新。在活动中,我已经实现了从服务接收位置更新的本地广播接收器。我的代码在绘制路线时起作用,但这不是最聪明的方法,因为我必须继续清除地图以避免路线过度绘制。有没有更好更有效的方法来使用map v2?
public class TrackingService extends Service
{
// ...
@Override
public void onLocationChanged(Location location)
{
//...
dataSource.open();
dataSource.insertLocation(location.getLatitude(), location.getLongitude())
dataSource.close();
broadcastLocation(location);
}
private void broadcastLocation(Location location)
{
Intent intent = new Intent(ACTION_RECEIVE_LOCATION);
intent.putExtra(KEY_NEW_LOCATION, location);
sendBroadcast(intent);
}
}
public class TrackingActivity extends Activity
{
private GoogleMap googleMap;
private PolylineOptions polylineOptions;
private RoutesDataSource dataSource;
private IntentFilter intentFilter;
private BroadcastReceiver receiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
googleMap.clear();
Location location = intent.getParcelableExtra(TrackingService.KEY_NEW_LOCATION);
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, CAMERA_ZOOM);
googleMap.animateCamera(update);
polylineOptions.add(latLng);
googleMap.addPolyline(polylineOptions);
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracking);
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
polylineOptions = new PolylineOptions().width(POLYLINE_WIDTH).color(Color.RED);
dataSource = new RoutesDataSource(this);
intentFilter = new IntentFilter(TrackingService.ACTION_RECEIVE_LOCATION);
registerReceiver(receiver, intentFilter);
drawRouteOnCreate();
}
private void drawRouteOnCreate()
{
dataSource.open();
List<LatLng> locations = dataSource.getAllLocations(id);
dataSource.close();
polylineOptions.addAll(locations);
googleMap.addPolyline(polylineOptions);
}
@Override
protected void onDestroy()
{
unregisterReceiver(receiver);
super.onDestroy();
}
// ...
}
我最终使用了setPoints!
private Polyline route;
private List<LatLng> points;
@Override
public void onReceive(Context context, Intent intent)
{
// ...
points.add(latLng));
route.setPoints(points);
}
private void drawRouteOnCreate()
{
route = map.addPolyline(new PolylineOptions().width(6).color(Color.RED));
dbAdapter.open();
points = dbAdapter.getAllLocations();
dbAdapter.close();
route.setPoints(points);
}
答案 0 :(得分:0)
方法addPolyline返回一个Polyline对象,您可以在后续调用中使用方法setPoints来设置完整路径(包括新位置)。我不知道如果路线是地图上唯一的元素,这会产生很大的不同。但是如果你有例如额外的标记肯定比总是清除整个地图更好。