0

Я пытаюсь создать приложение, которое отслеживает маршрут пользователя и получает доступ к GPS, чтобы получить их местоположение. Затем я буду рисовать полилинии между этими точками, чтобы показать маршрут. Мне было интересно, как именно я буду зацикливаться, чтобы продолжать получать очки, а затем, как затем помещать их на карты для отображения маршрута. Это то, что у меня есть до сих пор. Будет ли этот цикл работать, чтобы поместить точки в список? Если не так, как я буду делать то, что хочу достичь?Android Polyline App, чтобы нанести на карту маршрут пользователя

Одна из небольших проблем заключается в том, что он говорит, что переменная mContext может не быть инициализирована. Это было после того, как я добавил

public GPSTracker(){ 
     arrayPoints = new ArrayList<LatLng>(); 
    } 

GPSTracker класс: импорт com.google.android.gms.maps.model.LatLng;

import java.util.ArrayList; 

import android.app.AlertDialog; 
import android.app.Service; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.provider.Settings; 
import android.util.Log; 

import javax.crypto.spec.GCMParameterSpec; 

public class GPSTracker extends Service implements LocationListener { 

    //array with latitude and longitude points for polylines 
    public static ArrayList<LatLng> arrayPoints; 
    // intent.putExtra("arrayPoints", arrayPoints); 

    private final Context mContext; 

    // flag for GPS status 
    boolean isGPSEnabled = false; 

    // flag for network status 
    boolean isNetworkEnabled = false; 

    // flag for GPS status 
    boolean canGetLocation = false; 

    Location location; // location 
    double latitude; // latitude 
    double longitude; // longitude 

    // The minimum distance to change Updates in meters 
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 

    // The minimum time between updates in milliseconds 
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute 

    // Declaring a Location Manager 
    protected LocationManager locationManager; 

    public GPSTracker(Context context) { 
     this.mContext = context; 
     getLocation(); 
    } 
    public GPSTracker(){ 
     arrayPoints = new ArrayList<LatLng>(); 
    } 
    public ArrayList<LatLng> getLocation() { 
     try { 
      locationManager = (LocationManager) mContext 
        .getSystemService(LOCATION_SERVICE); 

      // getting GPS status 
      isGPSEnabled = locationManager 
        .isProviderEnabled(LocationManager.GPS_PROVIDER); 

      // getting network status 
      isNetworkEnabled = locationManager 
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      if (!isGPSEnabled && !isNetworkEnabled) { 
       // no network provider is enabled 
      } else { 
       this.canGetLocation = true; 
       // First get location from Network Provider 
       if (isNetworkEnabled) { 
        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("Network", "Network"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
       // if GPS Enabled get lat/long using GPS Services 
       if (isGPSEnabled) { 
        if (location == null) { 
         locationManager.requestLocationUpdates(
           LocationManager.GPS_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
         Log.d("GPS Enabled", "GPS Enabled"); 

         while(locationManager != null) { 
          location = locationManager 
            .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
          if (location != null) { 
           latitude = location.getLatitude(); 
           longitude = location.getLongitude(); 
           arrayPoints.add(new LatLng(latitude, longitude)); 

          } 
         } 
        } 
       } 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 


     return arrayPoints; 
    } 

    public ArrayList<LatLng> getPoints(){ 
     return arrayPoints; 
    } 
    /** 
    * Stop using GPS listener 
    * Calling this function will stop using GPS in your app 
    * */ 
    public void stopUsingGPS(){ 
     if(locationManager != null){ 
      locationManager.removeUpdates(GPSTracker.this); 
     } 
    } 

    /** 
    * Function to get latitude 
    * */ 
    public double getLatitude(){ 
     if(location != null){ 
      latitude = location.getLatitude(); 
     } 

     // return latitude 
     return latitude; 
    } 

    /** 
    * Function to get longitude 
    * */ 
    public double getLongitude(){ 
     if(location != null){ 
      longitude = location.getLongitude(); 
     } 

     // return longitude 
     return longitude; 
    } 

    /** 
    * Function to check GPS/wifi enabled 
    * @return boolean 
    * */ 
    public boolean canGetLocation() { 
     return this.canGetLocation; 
    } 

    /** 
    * Function to show settings alert dialog 
    * On pressing Settings button will lauch Settings Options 
    * */ 
    public void showSettingsAlert(){ 
     AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

     // Setting Dialog Title 
     alertDialog.setTitle("GPS is disabled"); 

     // Setting Dialog Message 
     alertDialog.setMessage("GPS is not enabled. Turn it on in settings."); 

     // On pressing Settings button 
     alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog,int which) { 
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       mContext.startActivity(intent); 
      } 
     }); 

     // on pressing cancel button 
     alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.cancel(); 
      } 
     }); 

     // Showing Alert Message 
     alertDialog.show(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
    } 

    @Override 
    public IBinder onBind(Intent arg0) { 
     return null; 
    } 

MapsActivity Класс:

private GoogleMap mMap; // Might be null if Google Play services APK is not available. 
    private GoogleApiClient mGoogleApiClient; 
    private LocationRequest mLocationRequest; 
    private GPSTracker gpsTracker; 
    public static final String TAG = MapsActivity.class.getSimpleName(); 
    Location Location; 

    public MapsActivity(){ 
     gpsTracker = new GPSTracker(); 
    } 

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

     mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
       new LatLng(40.0139, -105.1507), 3)); 

     try { 

      GPSTracker gps = new GPSTracker(MapsActivity.this); 

      // check if GPS enabled 
      if (gps.canGetLocation()) { 

       double latitude = gps.getLatitude(); 
       double longitude = gps.getLongitude(); 

       // \n is for new line 
       Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); 
      } else { 
       // can't get location 
       // GPS or Network is not enabled 
       // Ask user to enable GPS/network in settings 
       gps.showSettingsAlert(); 
      } 

      // Loading map 
      initializeMap(); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    private void initializeMap() { 

     if (mMap == null) { 
      mMap = ((MapFragment) getFragmentManager().findFragmentById(
        R.id.map)).getMap(); 

      // check if map is created successfully or not 
      if (mMap == null) { 
       Toast.makeText(getApplicationContext(), 
         "Error: Unable to create map", Toast.LENGTH_SHORT) 
         .show(); 
      } 

      mMap.setMyLocationEnabled(true); 
      mMap.getUiSettings().setMyLocationButtonEnabled(true); 
      mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); 

     } 
    } 

    public void onMapReady(GoogleMap mMap) { 
     ArrayList<LatLng> arrayPoints = gpsTracker.getPoints(); 

     if (arrayPoints.size() > 1) { 

      PolylineOptions polyline_options = new PolylineOptions() 
        .addAll(arrayPoints).color(Color.GREEN).width(2); 

      Polyline polyline = mMap.addPolyline(polyline_options); 


     } 
    } 






    /* @Override 
    protected void onResume() { 
     super.onResume(); 
     setUpMapIfNeeded(); 
    }*/ 

    /** 
    * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly 
    * installed) and the map has not already been instantiated.. This will ensure that we only ever 
    * call {@link #setUpMap()} once when {@link #mMap} is not null. 
    * <p/> 
    * If it isn't installed {@link SupportMapFragment} (and 
    * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to 
    * install/update the Google Play services APK on their device. 
    * <p/> 
    * c * A an return to this FragmentActivity after following the prompt and correctly 
    * installing/updating/enabling the Google Play services. Since the FragmentActivity may not 
    * have been completely destroyed during this process (it is likely that it would only be 
    * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this 
    * method in {@link #onResume()} to guarantee that it will be called. 
    */ 
    private void setUpMapIfNeeded() { 
     // Do a null check to confirm that we have not already instantiated the map. 
     if (mMap == null) { 
      // Try to obtain the map from the SupportMapFragment. 
      mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) 
        .getMap(); 
      // Check if we were successful in obtaining the map. 
      if (mMap != null) { 
       setUpMap(); 
      } 
     } 
    } 


    private void setUpMap() { 
     mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker")); 
    } 
} 

Спасибо за помощь, скажите мне, если мне нужно уточнить более или показать меньше кода.

ответ

0

Просто попробуйте дать вам представление: вы можете отслеживать последние добавленные маркеры и возвращать текущее местоположение пользователя, основанное каждый раз в какое-то время, и если расстояние от текущего пользователя latLong и предыдущего маркера latLong больше определенного значение, добавьте новый маркер. итерация процесса, обновляющего предыдущий маркер, и пользовательский latLong. Просто подумайте, пожалуйста, сделайте снимок.