如何在谷歌地图上追踪路径?

时间:2015-10-14 10:58:52

标签: android google-maps navigation

我想创建一个导航应用。我能够创建从当前位置到目的地的折线路径。我想像谷歌导航应用程序一样创建它,意味着当目的地点没有到达时,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;
        }
    }
}

1 个答案:

答案 0 :(得分: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);