如何在地图上显示多段线



我试图显示多段线,当我把它放在onLocationResult中时,它显示了正确的线。

但是,我只希望它在用户单击开始按钮时显示多段线。所以我尝试将代码放入onClickListener中,屏幕只显示标记,而不显示行。

Location mLastLocation;
LocationRequest mLocationRequest;
private SupportMapFragment mapFragment;
private FusedLocationProviderClient mFusedLocationClient;
private FirebaseAuth myAuth;
private FirebaseDatabase mDatabase;
private DatabaseReference myRef;
private Marker currentUserLocationMarker;
private ArrayList<LatLng> points; //added
Polyline line;
private Button btnStartRun;
LatLng latLng;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_googls_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
points = new ArrayList<LatLng>();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
btnStartRun=findViewById(R.id.btnStartRun);
btnStartRun.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
points.add(latLng);//add points to the array
redrawLine();
myAuth=FirebaseAuth.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("OnlineUsers");//.child("OnlineUser");
DatabaseReference currentUserDB=mDatabase.child(myAuth.getCurrentUser().getUid());
currentUserDB.child("CurrentLatitude").setValue(mLastLocation.getLatitude());
currentUserDB.child("CurrentLongitude").setValue(mLastLocation.getLongitude());
}
}); 
}

这是我的onLocationResult

LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
mLastLocation = location;
latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));

}
}
};

这是我的redrawline()

private void redrawLine(){
mMap.clear();  //clears all Markers and Polylines
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);//set the colour and width of the polyline
for (int i = 0; i < points.size(); i++) {
LatLng point = points.get(i);
options.add(point);
}
addMarker(); //add Marker in current position
line = mMap.addPolyline(options); //add Polyline
}

谢谢。

您只是在点击按钮时添加点,但这是不正确的。每次获得onLocationChanged(或者您的位置回调(时,您都应该添加到点,否则,您将没有任何可绘制的线。

您的onLocationChanged(或回调(每次都应该调用refreshLine方法。

您的refreshLine方法应该有一个标志,例如hasStarted。如果hasStarted=false,则清除地图,但不要划线。如果hasStarted=true,则清除地图并绘制线。

在onClick侦听器中,只需设置hasStarted=true(或者,如果您希望它是一个切换,请说hasStarted=!hasStarted(。

最新更新