2015-10-14 71 views
0

我想創建一個導航應用程序。我可以創建從我的當前位置到目的地的多段線路徑。我想創建它像谷歌導航應用程序,意味着一個arrrow導航用戶連續路徑,而目的地點沒有到達。但我不知道我該怎麼做。 我嘗試了很多找到它,但無法找到它。請幫助我們。 我的地圖代碼如下。如何跟蹤谷歌地圖上的路徑?

public class NavigationActivity extends FragmentActivity implements LocationListener { 
    public static final String TAG_SLAT = "sourcelat"; 
    public static final String TAG_SLONG = "sourcelong"; 
    public static final String TAG_DLAT = "destinationlat"; 
    public static final String TAG_DLONG = "destinationg"; 

    private static LatLng Source = null; 
    private static LatLng Destination = null; 

    private GoogleMap map; 
    private SupportMapFragment fragment; 
    private LatLngBounds latlngBounds; 
    private Button bNavigation; 
    private Polyline newPolyline; 
    private Marker smarker; 
    private Marker dmarker; 
    Geocoder geocoder; 

    private boolean isTraveling = false; 
    private int width, height; 
    private String sourcelat; 
    private String sourcelong; 
    private String destinationg; 
    private String destinationlat; 
    double slat; 
    double slong; 
    double dlat; 
    double dlong; 
    double d; 
    double tempDistance; 
    String distance; 
    String ts; 

    List<Address> addresses; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     if (!isGooglePlayServicesAvailable()) { 
      finish(); 
     } 
     setContentView(R.layout.activity_navigation); 

     Intent in = getIntent(); 
     sourcelat = in.getStringExtra(TAG_SLAT); 
     destinationlat = in.getStringExtra(TAG_DLAT); 
     destinationg = in.getStringExtra(TAG_DLONG); 
     sourcelong = in.getStringExtra(TAG_SLONG); 


     slat=Double.parseDouble(sourcelat); 
     slong=Double.parseDouble(sourcelong); 
     dlat=Double.parseDouble(destinationlat); 
     dlong=Double.parseDouble(destinationg); 
     Source = new LatLng(slat,slong); 
     Destination = new LatLng(dlat,dlong); 

     getSreenDimanstions(); 

     fragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)); 
     map = fragment.getMap(); 
     map.setMyLocationEnabled(true); 
     ImageButton cureent_location = (ImageButton)findViewById(R.id.clocation); 
     cureent_location.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       LocationShow(); 
      } 
     }); 

       if (!isTraveling) { 
        isTraveling = true; 


        findDirections(Source.latitude, Source.longitude, Destination.latitude, Destination.longitude, GMapV2Direction.MODE_DRIVING); 


       } else { 
        isTraveling = false; 

       } 

    } 
    public double calculateDistance(double fromLatitude,double fromLongitude,double toLatitude,double toLongitude) 
    { 

     float results[] = new float[1]; 

     try { 
      Location.distanceBetween(fromLatitude, fromLongitude, toLatitude, toLongitude, results); 
     } catch (Exception e) { 
      if (e != null) 
       e.printStackTrace(); 
     } 
     if (Source.equals(Destination)){ 
      distance="0"; 
     } 
     else { 
      int dist = (int) results[0]; 
      if (dist <= 0) 
       return 0D; 

      DecimalFormat decimalFormat = new DecimalFormat("#.##"); 
      results[0] /= 1000D; 
      distance = decimalFormat.format(results[0]); 
      double d = Double.parseDouble(distance); 
      double speed = 40; 
      double time = d/speed; 
      ts = manual(time); 
      Log.v("fdf", String.valueOf(ts)); 


     } 
     return d; 
    } 
    private static String manual(double eta) { 
     int hour = (int) eta; 
     eta = (eta - hour) * 60; 
     int minutes = (int) eta; 
     eta = (eta - minutes) * 60; 
     int seconds = (int) eta; 
     eta = (eta - seconds) * 1000; 
     int ms = (int) eta; 
     //Log.d("ffgfh", String.valueOf(eta)); 
     return String.format("%dHr %dMin ", hour, minutes); 
    } 
    @Override 
    protected void onResume() { 

     super.onResume(); 
     latlngBounds = createLatLngBoundsObject(Source, Destination); 
     map.moveCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 150)); 

    } 

    public void handleGetDirectionsResult(ArrayList<LatLng> directionPoints) { 
     PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.RED); 
     MarkerOptions marker = new MarkerOptions().position(Source).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); 
     MarkerOptions marker1 = new MarkerOptions().position(Destination).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); 


     for(int i = 0 ; i < directionPoints.size() ; i++) 
     {   
      rectLine.add(directionPoints.get(i)); 


     } 
     if (newPolyline != null) 
     { 

      newPolyline.remove(); 
     } 
     newPolyline = map.addPolyline(rectLine); 
     //smarker = map.addMarker(marker); 
     dmarker = map.addMarker(marker1); 
     if (isTraveling) { 

      latlngBounds = createLatLngBoundsObject(Source, Destination); 
      map.animateCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 150)); 
      Dialog dialog_help = new Dialog(this); 
      dialog_help .requestWindowFeature(Window.FEATURE_NO_TITLE); 
      dialog_help.setContentView(R.layout.title_multi_selectitems_dialog); 

      calculateDistance(slat, slong, dlat, dlong); 
      TextView dis = (TextView) dialog_help.findViewById(R.id.distance); 
      dis.setText("Distance " + distance + "Km "); 
      TextView tim = (TextView) dialog_help.findViewById(R.id.time); 
      tim.setText("Time   " + ts); 
      dialog_help.setCancelable(true); 
      dialog_help.setTitle("Distance & Time"); 

      dialog_help.setCanceledOnTouchOutside(true); 
      dialog_help.show(); 

      dialog_help.getWindow().setGravity(Gravity.CENTER); 
      dialog_help.getWindow().setBackgroundDrawable(new ColorDrawable(Color.LTGRAY)); 
      dialog_help.getWindow().setLayout(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT); 
     } 
     else 
     { 

      map.animateCamera(CameraUpdateFactory.newLatLngBounds(latlngBounds, width, height, 150)); 
     } 

    } 

    private void getSreenDimanstions() 
    { 
     Display display = getWindowManager().getDefaultDisplay(); 
     width = display.getWidth(); 
     height = display.getHeight(); 
    } 

    private LatLngBounds createLatLngBoundsObject(LatLng firstLocation, LatLng secondLocation) 
    { 
     if (firstLocation != null && secondLocation != null) 
     { 
      LatLngBounds.Builder builder = new LatLngBounds.Builder(); 
      builder.include(firstLocation).include(secondLocation); 

      return builder.build(); 
     } 
     return null; 
    } 



    public void findDirections(double fromPositionDoubleLat, double fromPositionDoubleLong, double toPositionDoubleLat, double toPositionDoubleLong, String mode) 
    { 
     Map<String, String> map = new HashMap<String, String>(); 
     map.put(GetDirectionsAsyncTask.USER_CURRENT_LAT, String.valueOf(fromPositionDoubleLat)); 
     map.put(GetDirectionsAsyncTask.USER_CURRENT_LONG, String.valueOf(fromPositionDoubleLong)); 
     map.put(GetDirectionsAsyncTask.DESTINATION_LAT, String.valueOf(toPositionDoubleLat)); 
     map.put(GetDirectionsAsyncTask.DESTINATION_LONG, String.valueOf(toPositionDoubleLong)); 
     map.put(GetDirectionsAsyncTask.DIRECTIONS_MODE, mode); 

     GetDirectionsAsyncTask asyncTask = new GetDirectionsAsyncTask(this); 
     asyncTask.execute(map); 

    } 

    @Override 
    public void onLocationChanged(Location location) { 
     TextView cl = (TextView) findViewById(R.id.latlongLocation); 
     double latitude = location.getLatitude(); 
     double longitude = location.getLongitude(); 
     LatLng latLng = new LatLng(latitude, longitude); 
     map.addMarker(new MarkerOptions().position(latLng)); 
     map.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
     map.animateCamera(CameraUpdateFactory.zoomTo(5)); 

     geocoder = new Geocoder(this, Locale.getDefault()); 

     try { 
      addresses = geocoder.getFromLocation(latitude, longitude, 1); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     String address = addresses.get(0).getAddressLine(0); 
     String prmises = addresses.get(0).getAddressLine(1); 
     String city = addresses.get(0).getAddressLine(2); 
     String country = addresses.get(0).getAddressLine(3); 
     cl.setText(address+" "+prmises+" "+city+" " +country); 
    } 

    @Override 
    public void onStatusChanged(String s, int i, Bundle bundle) { 

    } 


    public void LocationShow() { 
     LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
     Criteria criteria = new Criteria(); 
     String bestProvider = locationManager.getBestProvider(criteria, true); 
     Location location = locationManager.getLastKnownLocation(bestProvider); 
     if (location != null) { 
      onLocationChanged(location); 
     } 
     locationManager.requestLocationUpdates(bestProvider, 20000, 0, this); 

    } 
    @Override 
    public void onProviderEnabled(String s) { 

    } 

    @Override 
    public void onProviderDisabled(String s) { 

    } 
    private boolean isGooglePlayServicesAvailable() { 
     int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); 
     if (ConnectionResult.SUCCESS == status) { 
      return true; 
     } else { 
      GooglePlayServicesUtil.getErrorDialog(status, this, 0).show(); 
      return false; 
     } 
    } 
} 

回答

0

也許你想創建一個具有多個點的線,它代表了用戶的每個位置的折線:

提供一個全局變量:

PolylineOptions pathOptions; 

@Override 
public View onCreate(Bundle savedInstanceState) { 
    ... 
    pathOptions = new PolylineOptions(); 
    ... 
} 


@Override 
public void onLocationChanged(Location location) { 
    ... 
    pathOptions.add(new LatLng(42.255, 10.142)); 
} 

並創建一個對象後PolylineOptions和Map調用:

Polyline userPath = map.addPolyline(pathOptions);