下面是我的代码在这里我添加了总线标记。现在我想要的是当我的网络服务每30秒呼叫一次,然后只有一个标记刷新而另一个标记覆盖。我想要的另一件事是当标记位置改变然后我的标记闪烁并移动到新位置但是我想添加动画以便用户感觉公共汽车在路上行驶。我怎样才能做到这一点?
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> 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<>();
Handler handler;
boolean doubleBackToExitPressedOnce = false;
ConnectionDetector cd;
Boolean isInternetPresent = false;
Circle circle;
Marker marker, busMarker;
String startLoc, endLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
FindViewById();
CheckGpsStatus();
}
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, 30000);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
} else {
apiShift();
handler = new Handler();
handler.postDelayed(runLocation, 30000);
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, "Sorry something went wrong..Try again", 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, "Sorry something went wrong..Try again", 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, "Sorry something went wrong..Try again", 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 {
// and check the result in onActivityResult().
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) {
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();
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");
List<String> wp = null;
for (int i = 0; i < json_user.length(); i++) {
try {
JSONObject obj = json_user.getJSONObject(i);
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);
startLoc = obj.getString("start_location");
endLocation = obj.getString("end_location");
} catch (JSONException e) {
e.printStackTrace();
}
}
sendRequest(startLoc, endLocation, wp);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onError(String message) {
Toast.makeText(MapActivity.this, "Sorry something went wrong..Try again", 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);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mylocation, 10));
} else {
}
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 (marker != null) {
marker.remove();
}
if (circle != null) {
circle.remove();
}
if (busMarker != null) {
busMarker.remove();
}
marker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location))
.title("My Location")
.position(mylocation));
circle = mMap.addCircle(new CircleOptions()
.center(mylocation)
.radius(1000)
.strokeColor(0x10000000)
.fillColor(0x10000000));
} else {
}
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");
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);
busMarker = 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, "Sorry something went wrong..Try again", Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
MapActivity.this.handler.postDelayed(MapActivity.this.runLocation, 30000);
}
};
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<>();
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_AZURE))
.title(route.startAddress)
.position(route.startLocation)));
for (int i = 0; i < route.jlegs.size(); i++) {
destinationMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
.title(route.jaddress.get(i))
.position(route.jlegs.get(i))));
}
destinationMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
.title(route.endAddress)
.position(route.endLocation)));
PolylineOptions polylineOptions = new PolylineOptions().
geodesic(true).
color(Color.parseColor("#00B3FD")).
width(10);
for (int i = 0; i < route.points.size(); i++)
polylineOptions.add(route.points.get(i));
polylinePaths.add(mMap.addPolyline(polylineOptions));
setUpMapIfNeeded();
}
}
}