Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/206.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何在谷歌地图上追踪路径?_Android_Google Maps_Navigation - Fatal编程技术网

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

Android 如何在谷歌地图上追踪路径?,android,google-maps,navigation,Android,Google Maps,Navigation,我想创建一个导航应用程序。我能够创建从当前位置到目标的多段线路径。我想创建一个像谷歌导航应用程序一样的应用程序,这意味着一个arrrow可以在用户没有到达目的地的情况下连续地导航到路径。但我不知道我该怎么做。 我费了好大劲才找到它,但没能找到。请帮帮我,伙计们。 我的地图代码如下 public class NavigationActivity extends FragmentActivity implements LocationListener { public static fina

我想创建一个导航应用程序。我能够创建从当前位置到目标的多段线路径。我想创建一个像谷歌导航应用程序一样的应用程序,这意味着一个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;
        }
    }
}
公共类导航活动扩展碎片活动实现LocationListener{
公共静态最终字符串标记\u SLAT=“sourcelat”;
公共静态最终字符串标记\u SLONG=“sourcelong”;
公共静态最终字符串标记_DLAT=“destinationlat”;
公共静态最终字符串标记\u DLONG=“destinationg”;
私有静态LatLng源=null;
专用静态LatLng目的地=null;
私人谷歌地图;
私有支持图片段;
私人停车场停车场;
私人航空;
私有多段线新建多段线;
私人标记器;
专用标记器;
地理编码器;
私有布尔值isTraveling=false;
私人int宽度、高度;
私有字符串sourcelat;
私有字符串源长;
私有字符串目的地;
私有字符串目的地;
双板条;
双长跑;
双dlat;
双德隆;
双d;
双温距;
串距;
字符串ts;
列出地址;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
如果(!isGooglePlayServicesAvailable()){
完成();
}
setContentView(R.layout.activity\u导航);
Intent in=getIntent();
sourcelat=in.getStringExtra(标签板条);
destinationlat=in.getStringExtra(标记);
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);
来源=新板条(板条、板条);
目的地=新机场(dlat、dlong);
getsreendimanstations();
片段=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map));
map=fragment.getMap();
map.setMyLocationEnabled(true);
ImageButton当前位置=(ImageButton)findViewById(R.id.clocation);
cureent_location.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
LocationShow();
}
});
如果(!isTraveling){
isTraveling=true;
findDirections(源.纬度,源.经度,目的地.纬度,目的地.经度,GMapV2Direction.MODE_驾驶);
}否则{
isTraveling=假;
}
}
公共双精度计算站(双精度纬度、双精度经度、双精度纬度、双精度经度)
{
浮动结果[]=新浮动[1];
试一试{
位置。距离(从纬度、经度、经度、经度、结果);
}捕获(例外e){
如果(e!=null)
e、 printStackTrace();
}
if(源等于(目标)){
距离=“0”;
}
否则{
int dist=(int)结果[0];

如果(dist可能需要创建一条多段线,其中包含多个点,表示用户的每个位置:

提供一个全局变量:

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对象和映射调用后:

Polyline userPath = map.addPolyline(pathOptions);