如何使巴士在谷歌地图上移动? [英] How to make bus moving on google map?

查看:120
本文介绍了如何使巴士在谷歌地图上移动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建巴士跟踪android应用程序和下面的代码工作正常。现在我想要的是,当巴士从一个地方移动到另一个地方时,我从m网络服务获得新的经纬度,所以公交车在新的位置上显示出来,但它不会从旧的地方移开。对于用户当前位置也是如此。我想每15秒清除一次用户和总线的旧位置。我怎样才能做到这一点?

I am creating bus tracking android app and below code in working fine. Now what I want that when bus move from one place to another and I am getting new latitude and longitude of bus from m web service so bus showing on new position but its not removing from old place. And same happening for user current location. I want to clear old position of user and bus every 15 seconds. How can I achieve this ?

public class MapActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback, DirectionFinderListener {

    private SQLiteHandler db;
    private SessionManager session;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    PendingResult<LocationSettingsResult> result;
    final static int REQUEST_LOCATION = 199;
    ImageView btnPreference, btnLocation, btnPassword, btnProfile;
    Spinner spinnerShift, spinnerStops;
    List<String> ShiftArrayList = new ArrayList<String>();
    final List<Integer> ShiftValueArrayList = new ArrayList<Integer>();
    List<String> StopArrayList = new ArrayList<String>();
    final List<Integer> StopValueArrayList = new ArrayList<Integer>();
    int selected_shift, selected_stop;
    GridView gridView;
    private List<Routes> routeList = new ArrayList<Routes>();
    private CustomListAdapter adapter;
    GPSTracker gps;
    List<Marker> originMarkers = new ArrayList<>();
    List<Marker> currentLoc = new ArrayList<>();
    List<Marker> MyLocation1 = new ArrayList<>();
    List<Marker> waypointsMarkers = new ArrayList<>();
    GoogleMap mMap;
    List<Marker> buslocation = new ArrayList<>();
    List<Marker> destinationMarkers = new ArrayList<>();
    List<Polyline> polylinePaths = new ArrayList<>();
    android.os.Handler handler;
    boolean doubleBackToExitPressedOnce = false;
    ConnectionDetector cd;
    Boolean isInternetPresent = false;

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

        FindViewById();

        CheckGpsStatus();

        ButtonCLickEvent();

    }

    public void FindViewById() {

        btnPreference = (ImageView) findViewById(R.id.btnPreference);
        btnLocation = (ImageView) findViewById(R.id.btnLocation);
        btnPassword = (ImageView) findViewById(R.id.btnPassword);
        btnProfile = (ImageView) findViewById(R.id.btnProfile);
        spinnerShift = (Spinner) findViewById(R.id.spinnerShift);
        spinnerStops = (Spinner) findViewById(R.id.spinnerStops);
        gridView = (GridView) findViewById(R.id.gridView);
    }

    public void ButtonCLickEvent() {

        btnPreference.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MapActivity.this, SetPreferenceActivity.class);
                startActivity(intent);
            }
        });

        btnPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MapActivity.this, ResetPasswordActivity.class);
                startActivity(intent);
            }
        });

        btnProfile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MapActivity.this, ProfileActivity.class);
                startActivity(intent);
            }
        });

    }

    public void CheckGpsStatus() {

        final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();
            mGoogleApiClient.connect();

            cd = new ConnectionDetector(getApplicationContext());
            isInternetPresent = cd.isConnectingToInternet();

            if (isInternetPresent){
                apiShift();
            }else {
                final SweetAlertDialog alert = new SweetAlertDialog(MapActivity.this, SweetAlertDialog.WARNING_TYPE);
                alert.setTitleText("No Internet");
                alert.setContentText("Please connect to internet..");
                alert.show();
            }



            handler = new Handler();
            handler.postDelayed(runLocation, 15000);


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

        } else {

            apiShift();

            handler = new Handler();
            handler.postDelayed(runLocation, 15000);


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

    public void apiShift() {

        VolleyWebService.makeJsonObjectRequest(MapActivity.this, Request.Method.GET, AppConfig.ShiftData, null, new VolleyResponseListener() {
            @Override
            public void onResponse(JSONObject response) {

                try {

                    JSONObject jObj = new JSONObject(String.valueOf(response));
                    JSONArray json_user = jObj.getJSONArray("Message");
                    for (int i = 0; i < json_user.length(); i++) {

                        try {

                            JSONObject obj = json_user.getJSONObject(i);
                            ShiftArrayList.add(obj.getString("shift_name"));
                            ShiftValueArrayList.add(Integer.valueOf(obj.getString("shift_id")));

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

                    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(MapActivity.this, R.layout.spinner, ShiftArrayList);
                    dataAdapter.notifyDataSetChanged();
                    spinnerShift.setAdapter(dataAdapter);

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

            @Override
            public void onError(String message) {
                Toast.makeText(MapActivity.this, "Server not responding..", Toast.LENGTH_SHORT).show();
            }
        });

        spinnerShift.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                selected_shift = Integer.parseInt(ShiftValueArrayList.get(position).toString());
                String shift_id = ShiftValueArrayList.get(position).toString();

                apiRoutes(shift_id);

                apiStops(shift_id);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    public void apiStops(final String shiftId) {

        String url = AppConfig.StopData + "shift_id=" + shiftId;

        VolleyWebService.makeJsonObjectRequest(MapActivity.this, Request.Method.GET, url, null, new VolleyResponseListener() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    StopArrayList.clear();
                    StopValueArrayList.clear();
                    JSONObject jObj = new JSONObject(String.valueOf(response));
                    JSONArray json_user = jObj.getJSONArray("Message");

                    for (int i = 0; i < json_user.length(); i++) {

                        try {

                            JSONObject obj = json_user.getJSONObject(i);
                            StopArrayList.add(obj.getString("stop_name"));
                            StopValueArrayList.add(Integer.valueOf(obj.getString("stop_id")));

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

                    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(MapActivity.this, R.layout.spinner_stop, StopArrayList);
                    dataAdapter.notifyDataSetChanged();
                    spinnerStops.setAdapter(dataAdapter);

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

            @Override
            public void onError(String message) {
                Toast.makeText(MapActivity.this, "Server not responding..", Toast.LENGTH_SHORT).show();
            }
        });

        spinnerStops.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                selected_stop = Integer.parseInt(StopValueArrayList.get(position).toString());
                String stop_id = StopValueArrayList.get(position).toString();

                apiDrawRoute(shiftId, stop_id);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    public void apiRoutes(String shift_id) {

        String url = AppConfig.RouteData + "shift_id_tabular=" + shift_id;

        VolleyWebService.makeJsonObjectRequest(MapActivity.this, Request.Method.GET, url, null, new VolleyResponseListener() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONObject mainObj = new JSONObject(String.valueOf(response));
                    if (mainObj != null) {
                        routeList.clear();
                        JSONArray list = mainObj.getJSONArray("Message");
                        if (list != null) {
                            for (int i = 0; i < list.length(); i++) {
                                JSONObject elem = list.getJSONObject(i);

                                Routes routes = new Routes();
                                routes.setSrNo(elem.getString("rn"));
                                routes.setName(elem.getString("location"));
                                routes.setTime(elem.getString("actual_time"));
                                routes.setStatus(elem.getString("run_status"));
                                routeList.add(routes);

                                }
                            }
                        }
                    }
                    adapter = new CustomListAdapter(MapActivity.this, routeList);
                    gridView.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(String message) {
                Toast.makeText(MapActivity.this, "Server not responding", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(30 * 1000);
        mLocationRequest.setFastestInterval(5 * 1000);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
        builder.setAlwaysShow(true);

        result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());

        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();

                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:

                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:

                        try {

                            status.startResolutionForResult(
                                    MapActivity.this,
                                    REQUEST_LOCATION);
                        } catch (IntentSender.SendIntentException e) {

                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:

                        break;
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("onActivityResult()", Integer.toString(resultCode));


        switch (requestCode) {
            case REQUEST_LOCATION:
                switch (resultCode) {
                    case Activity.RESULT_OK: {

                        break;
                    }
                    case Activity.RESULT_CANCELED: {

                        finish();
                        break;
                    }
                    default: {
                        break;
                    }
                }
                break;
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        super.onOptionsItemSelected(item);

        switch (item.getItemId()) {
            case R.id.logout:
                db = new SQLiteHandler(getApplicationContext());
                session = new SessionManager(getApplicationContext());
                session.setLogin(false);
                db.deleteUsers();


                Intent intent = new Intent(MapActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
        }
        return true;
    }

    public void apiDrawRoute(String shiftId, String stopId) {
        String url = AppConfig.RouteData + "shiftid=" + shiftId + "&stopid=" + stopId;
        VolleyWebService.makeJsonObjectRequest(MapActivity.this, Request.Method.GET, url, null, new VolleyResponseListener() {
            @Override
            public void onResponse(JSONObject response) {

                try {

                    JSONObject jObj = new JSONObject(String.valueOf(response));
                    JSONArray json_user = jObj.getJSONArray("Message");

                    for (int i = 0; i < json_user.length(); i++) {

                        try {

                            JSONObject obj = json_user.getJSONObject(i);

                            List<String> wp = new ArrayList<String>();

                            for (int w1 = 0; w1 < json_user.length(); w1++) {
                                wp.add(obj.getString("waypoints_latitude") + ',' + obj.getString("waypoints_longitude") + '|');
                            }
                            sendRequest(obj.getString("start_location"), obj.getString("end_location"), wp);

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

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

            @Override
            public void onError(String message) {
                Toast.makeText(MapActivity.this, "Server not responding..", Toast.LENGTH_SHORT).show();
            }
        });

        spinnerShift.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                selected_shift = Integer.parseInt(ShiftValueArrayList.get(position).toString());
                String shift_id = ShiftValueArrayList.get(position).toString();

                apiRoutes(shift_id);

                apiStops(shift_id);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.clear();
        MyLocation1.clear();
        gps = new GPSTracker(MapActivity.this);
        if (gps.CanGetLocation()) {
            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();

            LatLng mylocation = new LatLng(latitude, longitude);

            if (MyLocation1 != null) {
                for (Marker marker : MyLocation1) {
                    marker.remove();
                }
            }
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mylocation, 10));

            MyLocation1.add(mMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.curr_location))
                    .title("My Location")
                    .position(mylocation)));
            Circle circle = mMap.addCircle(new CircleOptions()
                    .center(mylocation)
                    .radius(1000)
                    .strokeColor(0x10000000)
                    .fillColor(0x10000000));
        } else {
            //gps.showSettingsAlert();
        }
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {


            return;
        }
        mMap.setMyLocationEnabled(true);
    }


    public Runnable runLocation = new Runnable() {
        @Override
        public void run() {

            gps = new GPSTracker(MapActivity.this);

            MyLocation1.clear();
            if (gps.CanGetLocation()) {
                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();
                LatLng mylocation = new LatLng(latitude, longitude);

                if (MyLocation1 != null) {
                    for (Marker marker : MyLocation1) {
                        marker.remove();
                    }
                }

                MyLocation1.add(mMap.addMarker(new MarkerOptions()
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.curr_location))
                        .title("My Location")
                        .position(mylocation)));
                Circle circle = mMap.addCircle(new CircleOptions()
                        .center(mylocation)
                        .radius(1000)
                        .strokeColor(0x10000000)
                        .fillColor(0x10000000));
            } else {
                // gps.showSettingsAlert();
            }
            String tag_json_obj = "json_obj_req";
            String url = AppConfig.RouteData + "i=1&" + "y=1";

            JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    try {

                        JSONObject jObj = new JSONObject(String.valueOf(response));
                        JSONArray json_user = jObj.getJSONArray("Message");
                        currentLoc.clear();
                        for (int i = 0; i < json_user.length(); i++) {

                            try {

                                JSONObject obj = json_user.getJSONObject(i);

                                Double currLat = obj.getDouble("actual_lat");
                                Double currLong = obj.getDouble("actual_long");
                                LatLng hcmus = new LatLng(currLat, currLong);
                                currentLoc.add(mMap.addMarker(new MarkerOptions()
                                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus))
                                        .title("Bus No" + obj.getString("bus_id"))
                                        .position(hcmus)));

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

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MapActivity.this, "Server not responding..", Toast.LENGTH_SHORT).show();
                }
            });

            // Adding request to request queue
            AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

            MapActivity.this.handler.postDelayed(MapActivity.this.runLocation, 15000);
        }

    };

    private void sendRequest(String Sl, String El, List Wp) {
        String origin = Sl.toString();
        String destination = El.toString();
        List waypoints = Wp;
        if (origin.isEmpty()) {
            Toast.makeText(this, "Please enter origin address!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (destination.isEmpty()) {
            Toast.makeText(this, "Please enter destination address!", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            new DirectionFinder(MapActivity.this, origin, destination, waypoints).execute();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDirectionFinderStart() {


        if (originMarkers != null) {
            for (Marker marker : originMarkers) {
                marker.remove();
            }
        }

        if (destinationMarkers != null) {
            for (Marker marker : destinationMarkers) {
                marker.remove();
            }
        }

        if (polylinePaths != null) {
            for (Polyline polyline : polylinePaths) {
                polyline.remove();
            }
        }
    }

    @Override
    public void onDirectionFinderSuccess(List<Route> routes) {
        polylinePaths = new ArrayList<>();
        originMarkers = new ArrayList<>();
        destinationMarkers = new ArrayList<>();
        waypointsMarkers = new ArrayList<>();
        buslocation = new ArrayList<>();
        mMap.clear();

        for (Route route : routes) {
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
            ((TextView) findViewById(R.id.tvDuration)).setText(route.duration.text);
            ((TextView) findViewById(R.id.tvDistance)).setText(route.distance.text);

            originMarkers.add(mMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
                    .title(route.startAddress)
                    .position(route.startLocation)));
//            waypointsMarkers.add(mMap.addMarker(new MarkerOptions()
//                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green))
//                    .title(route.waypointsAddress)
//                    .position(route.waypointsLocation)));
            for (int i = 0; i < route.jlegs.size(); i++) {
                destinationMarkers.add(mMap.addMarker(new MarkerOptions()
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE))
                        .title(route.jaddress.get(i))
                        .position(route.jlegs.get(i))));
            }
            destinationMarkers.add(mMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE))
                    .title(route.endAddress)
                    .position(route.endLocation)));
//            final LatLng MELBOURNE = new LatLng(24.571982, 73.725597);
//            buslocation.add(mMap.addMarker(new MarkerOptions()
//                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus))
//                    .title("Bus Location")
//                    .position(MELBOURNE)));
//            final LatLng MELBOURNE = new LatLng(24.571982, 73.725597);


            PolylineOptions polylineOptions = new PolylineOptions().
                    geodesic(true).
                    color(Color.BLUE).
                    width(5);

            for (int i = 0; i < route.points.size(); i++)
                polylineOptions.add(route.points.get(i));

            polylinePaths.add(mMap.addPolyline(polylineOptions));

//            setUpMapIfNeeded();
        }
    }



    @Override
    public void onBackPressed() {
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed();
            return;
        }

        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);
    }
}


推荐答案

清洁并在每次更新中重新载入您的位置列表。

Clean and Reload Your Location List On Every Single Update.!

这篇关于如何使巴士在谷歌地图上移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆