Android Studio: Как нарисовать маршрут в реальном времени и сохранить его? - PullRequest
0 голосов
/ 08 ноября 2019

Я работаю над проектом, чтобы нарисовать путь на картах Google, перемещаясь из моего местоположения для. Я хочу знать, как сохранить маршрут, который я создал.

Это мой MainActivity:

public class MainActivity extends AppCompatActivity implements
    OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    com.google.android.gms.location.LocationListener {

Button btnStart;
int flag;

private GoogleMap mMap;

private Polyline gpsTrack;
private SupportMapFragment mapFragment;
private GoogleApiClient googleApiClient;
private LatLng lastKnownLatLng;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnStart = findViewById(R.id.btnStart);

    mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    if (googleApiClient == null) {
        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    PolylineOptions polylineOptions = new PolylineOptions();
    polylineOptions.color(Color.RED);
    polylineOptions.width(10);
    gpsTrack = mMap.addPolyline(polylineOptions);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mMap = googleMap;

    mMap.setMinZoomPreference(6.6f);
    mMap.setMaxZoomPreference(20.20f);

    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setMyLocationButtonEnabled(true);

    LocationServices.getFusedLocationProviderClient(this).getLastLocation()
            .addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    if (location != null){
                        Log.i("teste", "deu");

                         LatLng atual = new LatLng(location.getLatitude(), location.getLongitude());
                         mMap.addMarker(new MarkerOptions().position(atual).title("Localizção 
atual"));
                         mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(atual, 15));

                    }else {
                        Log.i("teste", "n deu");
                    }
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {

                }
            });

}


@Override
protected void onStart() {
    googleApiClient.connect();
    super.onStart();
}

@Override
protected void onStop() {
    googleApiClient.disconnect();
    super.onStop();
}

@Override
protected void onPause() {
    super.onPause();
    stopLocationUpdates();
}

@Override
public void onResume() {
    super.onResume();
    if (googleApiClient.isConnected()) {
        //startLocationUpdates();
    }
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    if (googleApiClient.isConnected()) {
        //startLocationUpdates();
    }
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onLocationChanged(Location location) {
    lastKnownLatLng = new LatLng(location.getLatitude(), location.getLongitude());
    updateTrack();
}

protected void startLocationUpdates() {
    LocationRequest locationRequest = new LocationRequest();
    locationRequest.setInterval(15 * 1000);
    locationRequest.setFastestInterval(5 * 1000);
    locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);


    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, 
this);
}

protected void stopLocationUpdates() {
    LocationServices.FusedLocationApi.removeLocationUpdates(
            googleApiClient, this);
}

private void updateTrack() {
    List<LatLng> points = gpsTrack.getPoints();
    points.add(lastKnownLatLng);
    gpsTrack.setPoints(points);

}

public void socorro(View v) {

    switch (v.getId()) {
        case R.id.btnStart:
            startLocationUpdates();
            btnStart.setBackgroundResource(R.drawable.stop);
            break;

    }
 }
}

XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">

<fragment
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity" />

<LinearLayout

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="70dp">
<Button
    android:id="@+id/btnStart"
    android:layout_width="130dp"
    android:layout_height="130dp"
    android:onClick="socorro"
    android:background="@drawable/rec"

    />

</LinearLayout>

</RelativeLayout>

Это приложение работает намой мобильный телефон, каждый раз, когда обнаруживается новое местоположение, я добавляю последнюю точку LatLng к моей полилинии. Я хочу нарисовать путь, и после того, как я нажму кнопку СТОП, очистите полилинию и сохраните маршрут в базе данных:

APP

...