Sei sulla pagina 1di 19

package com.abistech.

dashboard;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import

android.app.ActivityManager;
android.app.AlertDialog;
android.app.DatePickerDialog;
android.app.ProgressDialog;
android.content.Context;
android.content.DialogInterface;
android.content.Intent;
android.graphics.Bitmap;
android.graphics.BitmapFactory;
android.graphics.Canvas;
android.graphics.Color;
android.graphics.Paint;
android.graphics.Rect;
android.graphics.Typeface;
android.os.AsyncTask;
android.os.Bundle;
android.support.v4.widget.DrawerLayout;
android.support.v7.app.ActionBarActivity;
android.support.v7.app.ActionBarDrawerToggle;
android.support.v7.widget.Toolbar;
android.view.Gravity;
android.view.Menu;
android.view.MenuInflater;
android.view.View;
android.view.ViewGroup;
android.widget.AdapterView;
android.widget.ArrayAdapter;
android.widget.Button;
android.widget.CompoundButton;
android.widget.DatePicker;
android.widget.ImageView;
android.widget.LinearLayout;
android.widget.ListView;
android.widget.TextView;
android.widget.ToggleButton;

import
import
import
import
import
import
import
import
import
import
import
import
import
import
import

com.abistech.locationservice.LocationService;
com.abistech.utils.ErrorManagementSystem;
com.abistech.utils.HTTPConnection;
com.google.android.gms.maps.CameraUpdate;
com.google.android.gms.maps.CameraUpdateFactory;
com.google.android.gms.maps.GoogleMap;
com.google.android.gms.maps.SupportMapFragment;
com.google.android.gms.maps.model.BitmapDescriptor;
com.google.android.gms.maps.model.BitmapDescriptorFactory;
com.google.android.gms.maps.model.LatLng;
com.google.android.gms.maps.model.LatLngBounds;
com.google.android.gms.maps.model.Marker;
com.google.android.gms.maps.model.MarkerOptions;
com.google.android.gms.maps.model.PolylineOptions;
com.sothree.slidinguppanel.SlidingUpPanelLayout;

import
import
import
import
import
import

org.w3c.dom.Document;
org.w3c.dom.Element;
org.w3c.dom.Node;
org.w3c.dom.NodeList;
org.xml.sax.InputSource;
org.xml.sax.SAXException;

import
import
import
import
import
import
import
import
import
import
import

java.io.IOException;
java.io.StringReader;
java.text.ParseException;
java.text.SimpleDateFormat;
java.util.ArrayList;
java.util.Arrays;
java.util.Calendar;
java.util.Date;
java.util.HashMap;
java.util.List;
java.util.TimeZone;

import
import
import
import

javax.xml.parsers.DocumentBuilder;
javax.xml.parsers.DocumentBuilderFactory;
javax.xml.parsers.ParserConfigurationException;
javax.xml.xpath.XPathExpressionException;

public class Dashboard extends ActionBarActivity {


private GoogleMap mMap;
private ErrorManagementSystem ems = new ErrorManagementSystem();
//Temp variables
private String userId = "1";
private String userName = "Tarun Abichandani";
private Date activeDate = null;
private Button selectDate = null;
SimpleDateFormat sdfSQL = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String tripId;
private boolean flagSetToggleStateOFF = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yy");
selectDate = (Button) findViewById(R.id.datePickerButton);
activeDate = new Date();
selectDate.setText(sdf.format(activeDate));
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(userName);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_lay
out);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
Dashboard.this,
mDrawerLayout,
toolbar,
R.string.drawer_open,
R.string.drawer_close
) {

public void onDrawerClosed(View v) {


getSupportActionBar().setTitle(userName);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View v) {
getSupportActionBar().setTitle("Select a Trip");
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACT
IVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServ
ices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
private void addListenerToToggleButton() {
ToggleButton toggle = (ToggleButton) findViewById(R.id.locServiceToggle)
;
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeList
ener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isCh
ecked) {
if(flagSetToggleStateOFF) {
if (isChecked) {
startLocService();
} else {
stopLocService();
}
}
}
});
}
private void startLocService() {
new AlertDialog.Builder(this)
.setTitle("Confirm Action")
.setMessage("Start Tracking Location ?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnC
lickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
String url = "http://abistarun.uphero.com/db_start_trip.
php";
new LaunchLocationService(url, "LogInTime="+sdfSQL.forma
t(new Date()), "UserId="+userId).execute();
}})
.setNegativeButton(android.R.string.no, new DialogInterface.OnCl
ickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{

setToggleButtonStateToOFF();
}}).show();
}
private void setToggleButtonStateToOFF() {
flagSetToggleStateOFF = false;
((ToggleButton) findViewById(R.id.locServiceToggle)).setChecked(false);
((ToggleButton) findViewById(R.id.locServiceToggle)).setBackgroundColor(
Color.RED);
flagSetToggleStateOFF = true;
}
private void setToggleButtonStateToON() {
flagSetToggleStateOFF = false;
((ToggleButton) findViewById(R.id.locServiceToggle)).setChecked(true);
((ToggleButton) findViewById(R.id.locServiceToggle)).setBackgroundColor(
Color.GREEN);
flagSetToggleStateOFF = true;
}
private void stopLocService() {
new AlertDialog.Builder(this)
.setTitle("Confirm Action")
.setMessage("Stop Tracking Location ?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnC
lickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
String url = "http://abistarun.uphero.com/db_stop_trip.p
hp";
new StopLocationService(url, "LogOutTime="+sdfSQL.format
(new Date()), "TripId="+tripId).execute();
}})
.setNegativeButton(android.R.string.no, new DialogInterface.OnCl
ickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
setToggleButtonStateToON();
}})
.show();
}
class LaunchLocationService extends AsyncTask<Void, String, String> {
HTTPConnection httpConnection = new HTTPConnection();
String url;
String[] parametersToPass;
ProgressDialog progress;
LaunchLocationService(String... params) {
url = params[0];
parametersToPass = new String[params.length-1];
for(int i=1; i<params.length; i++) {
parametersToPass[i-1] = params[i];
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();

progress = new ProgressDialog(Dashboard.this);


progress.show();
}
@Override
protected String doInBackground(Void... params) {
ems.storeLogs("HTTP request created");
String httpResponse = httpConnection.HTTPexecute(url, parametersToPa
ss);
return httpResponse;
}
@Override
protected void onPostExecute(String httpResponse) {
super.onPostExecute(httpResponse);
progress.dismiss();
if(httpResponse!=null) {
ems.storeLogs("HTTP request returned:\t" + httpResponse);
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInsta
nce();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(httpRespon
se));
Document dom = db.parse(is);
String status = HTTPConnection.parseXMLusingXpath(dom, "/xml
/body/status");
tripId = HTTPConnection.parseXMLusingXpath(dom, "/xml/body/t
ripId");
System.out.println(status);
if (status.equals("Success")) {
Intent locServiceIntent = new Intent(Dashboard.this, Loc
ationService.class);

}
}
}
}

locServiceIntent.putExtra("userId", userId);
locServiceIntent.putExtra("tripId", tripId);
startService(locServiceIntent);
setColorOfToggleButton(Color.GREEN);
} else {
//Throw error cannot start tracking
setToggleButtonStateToOFF();
ems.handleError(2,null,dom);
}
catch (ParserConfigurationException e) {
ems.handleError(1,e, null);
catch (SAXException e) {
ems.handleError(1, e, null);
catch (IOException e) {
ems.handleError(1, e, null);
catch (XPathExpressionException e) {
ems.handleError(1,e,null);

}
}
}
}
private void setColorOfToggleButton(int color) {
((ToggleButton) findViewById(R.id.locServiceToggle)).setBackgroundColor(
color);
}

class StopLocationService extends AsyncTask<Void, String, String> {


HTTPConnection httpConnection = new HTTPConnection();
String url;
String[] parametersToPass;
ProgressDialog progress;
StopLocationService(String... params) {
url = params[0];
parametersToPass = new String[params.length-1];
for(int i=1; i<params.length; i++) {
parametersToPass[i-1] = params[i];
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(Dashboard.this);
progress.show();
}
@Override
protected String doInBackground(Void... params) {
ems.storeLogs("HTTP request created");
String httpResponse = httpConnection.HTTPexecute(url, parametersToPa
ss);
return httpResponse;
}
@Override
protected void onPostExecute(String httpResponse) {
super.onPostExecute(httpResponse);
progress.dismiss();
if(httpResponse!=null) {
ems.storeLogs("HTTP request returned:\t" + httpResponse);
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInsta
nce();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(httpRespon
se));
Document dom = db.parse(is);
String status = HTTPConnection.parseXMLusingXpath(dom, "/xml
/body/status");
if (status.equals("Success")) {
Intent locServiceIntent = new Intent(Dashboard.this, Loc
ationService.class);
locServiceIntent.putExtra("userId", userId);
locServiceIntent.putExtra("tripId", tripId);
stopService(locServiceIntent);
populateDrawerInformation();
setColorOfToggleButton(Color.RED);
} else {
//Throw error cannot start tracking
setToggleButtonStateToOFF();
ems.handleError(2,null,dom);
}

} catch (ParserConfigurationException e) {
ems.handleError(1,e, null);
} catch (SAXException e) {
ems.handleError(1, e, null);
} catch (IOException e) {
ems.handleError(1, e, null);
} catch (XPathExpressionException e) {
ems.handleError(1,e,null);
}
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_dashboard, menu);
return true;
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
addListenerToToggleButton();
if(isMyServiceRunning(LocationService.class)) {
setToggleButtonStateToON();
} else {
new AlertDialog.Builder(this)
.setTitle("Confirm Action")
.setMessage("Do you want to start Tracking ?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int whichBut
ton) {
setToggleButtonStateToON();
String url = "http://abistarun.uphero.com/db_start_t
rip.php";
new LaunchLocationService(url, "LogInTime=" + sdfSQL
.format(new Date()), "UserId=" + userId).execute();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.
OnClickListener() {
public void onClick(DialogInterface dialog, int whichBut
ton) {
setToggleButtonStateToOFF();
populateDrawerInformation();
}
}).show();
}
}
private void populateDrawerInformation() {
String date = sdfSQL.format(activeDate).split(" ")[0];
String url = "http://abistarun.uphero.com/db_get_usertrips.php";
new HTTPConnectionThreadToPopulateTripdetails(url, "UserId="+userId, "Da
te="+date).execute();

}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmen
tById(R.id.map))
.getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker marker) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
if (marker.getTitle() != null) {
LinearLayout info = new LinearLayout(Dashboard.this);
info.setOrientation(LinearLayout.VERTICAL);
TextView startTime = new TextView(Dashboard.this);
startTime.setTextColor(Color.BLACK);
startTime.setGravity(Gravity.CENTER);
startTime.setTypeface(null, Typeface.BOLD);
startTime.setText(marker.getTitle().toString().split("to")[0
].trim());
TextView to = new TextView(Dashboard.this);
to.setTextColor(Color.BLACK);
to.setGravity(Gravity.CENTER);
to.setTypeface(null, Typeface.BOLD);
to.setText("to");
TextView endTime = new TextView(Dashboard.this);
endTime.setTextColor(Color.BLACK);
endTime.setGravity(Gravity.CENTER);
endTime.setTypeface(null, Typeface.BOLD);
endTime.setText(marker.getTitle().toString().split("to")[1].
trim());
info.addView(startTime);
info.addView(to);
info.addView(endTime);
return info;
}
return null;
}
});
}

public void dateChange(View view) {


final Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
calendar.setTime(activeDate);
DatePickerDialog dpd = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
selectDate.setText(dayOfMonth + "-" + (monthOfYear + 1)
+ "-" + year);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, monthOfYear);
calendar.set(Calendar.DATE, dayOfMonth);
activeDate = calendar.getTime();
populateDrawerInformation();
//finish();
}
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), ca
lendar.get(Calendar.DAY_OF_MONTH));
dpd.show();
}
class HTTPConnectionThreadToPopulateTripdetails extends AsyncTask<Void, Void
, String> {
HTTPConnection httpConnection = new HTTPConnection();
ErrorManagementSystem ems = new ErrorManagementSystem();
String url;
String[] parametersToPass;
HashMap<Integer, Integer> tripIdMap = new HashMap<Integer, Integer>();
HashMap<Integer, String> logInMap = new HashMap<Integer, String>();
HashMap<Integer, String> logOutMap = new HashMap<Integer, String>();
//HashMap<Integer, Integer> logOutReasonMap = new HashMap<Integer, Integ
er>();
ProgressDialog progress = new ProgressDialog(Dashboard.this);
HTTPConnectionThreadToPopulateTripdetails(String... params) {
url = params[0];
parametersToPass = new String[params.length - 1];
for (int i = 1; i < params.length; i++) {
parametersToPass[i - 1] = params[i];
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progress.setMessage("Please wait");
progress.show();
}
@Override
protected String doInBackground(Void... params) {
ems.storeLogs("HTTP request created");
String httpResponse = httpConnection.HTTPexecute(url, parametersToPa

ss);
return httpResponse;
}
@Override
protected void onPostExecute(String httpResponse) {
super.onPostExecute(httpResponse);
progress.dismiss();
if (httpResponse != null) {
ems.storeLogs("HTTP request returned:\t" + httpResponse);
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInsta
nce();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(httpRespon
se));
Document dom = db.parse(is);
int tripCnt = 0;
List<String> tripNameList = new ArrayList<String>();
String status = HTTPConnection.parseXMLusingXpath(dom, "/xml
/body/status");
if (status.equals("Success")) {
( (DrawerLayout) findViewById(R.id.drawer_layout)).openD
rawer(Gravity.LEFT);
NodeList nl = dom.getElementsByTagName("tripDetails");
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
if (nl.item(i).getNodeType() == Node.ELEMENT_NOD
E) {
Element el = (Element) nl.item(i);
if (el.getNodeName().contains("tripDetails")
) {
int tripId = Integer.parseInt(el.getElem
entsByTagName("tripId").item(0).getTextContent());
String tripName = el.getElementsByTagNam
e("tripName").item(0).getTextContent();
String logInTime = el.getElementsByTagNa
me("logInTime").item(0).getTextContent();
String logOutTime = el.getElementsByTagN
ame("logOutTime").item(0).getTextContent();
//int logOutReason = Integer.parseInt(el
.getElementsByTagName("logOutReason").item(0).getTextContent());
tripIdMap.put(tripCnt, tripId);
tripNameList.add("Trip "+(i+1));
//tripNameList.add(tripName);
logInMap.put(tripCnt, logInTime);
logOutMap.put(tripCnt, logOutTime);
//logOutReasonMap.put(tripCnt, logOutRea
son);
tripCnt++;
}
}
}
String[] listViewValues = Arrays.copyOf(tripNameList
.toArray(), tripNameList.size(), String[].class);

ListView listView = (ListView) findViewById(R.id.lef


t_drawer);
ArrayAdapter<String> adapter = new ArrayAdapter<Stri
ng>(Dashboard.this,
android.R.layout.simple_list_item_1, android
.R.id.text1, listViewValues);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnIt
emClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, V
iew view, int position, long id) {
populateSlidingDrawer(position);
}
});
}
} else {
ems.handleError(2,null,dom);
}
} catch (ParserConfigurationException e) {
ems.handleError(1,e, null);
} catch (SAXException e) {
ems.handleError(1, e, null);
} catch (IOException e) {
ems.handleError(1, e, null);
} catch (XPathExpressionException e) {
ems.handleError(1,e,null);
}
}
}
private void populateSlidingDrawer(int position) {
SimpleDateFormat sdfSlidingDrawerFormat = new SimpleDateFormat("dd M
MM yyyy HH:mm:ss");
TextView logIn = (TextView) findViewById(R.id.loginTime);
TextView logOut = (TextView) findViewById(R.id.logoutTime);
TextView totalHours = (TextView) findViewById(R.id.totalHours);
try {
Date logInTime = sdfSQL.parse(logInMap.get(position));
logIn.setText("LogIn Time:
"+sdfSlidingDrawerFormat.format(lo
gInTime));
Date logOutTime = sdfSQL.parse(logOutMap.get(position));
logOut.setText("LogOut Time: "+sdfSlidingDrawerFormat.format(log
OutTime));
long
long
long
long

diff = logOutTime.getTime() - logInTime.getTime();


seconds = diff / 1000 % 60;
minutes = (diff / (60*1000))%60;
hours = (diff / (60*60*1000))%60;

totalHours.setText("Total hours:
min : "+seconds+"sec");
} catch (ParseException e) {
ems.handleError(1,e,null);
}

"+hours+" hrs : "+minutes+"

String url = "http://abistarun.uphero.com/db_get_locations.php";


new HTTPConnectionThreadToPopulateMap(url, "UserId="+userId, "TripId
="+tripIdMap.get(position)).execute();
}
}
class HTTPConnectionThreadToPopulateMap extends AsyncTask<Void, Void, String
> {
HTTPConnection httpConnection = new HTTPConnection();
ErrorManagementSystem ems = new ErrorManagementSystem();
String url;
String[] parametersToPass;
PolylineOptions pathPolyLine;
HashMap<Integer, PolylineOptions> polylineMap = new HashMap<Integer, Pol
ylineOptions>();
HashMap<Integer, Integer> markerMap = new HashMap<Integer, Integer>(); /
/value is end marker: startMarker = endMaker - 1
int legendId = 1;
Location prevLoc;
float totalDistance = 0;
ProgressDialog progress = new ProgressDialog(Dashboard.this);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
Location[] junkBuffer = new Location[3];
Location[] bulkBuffer = new Location[2];
private double junkThreshold = 300;
private double bulkThreshold = 100;
private int markerCount = 1;
private DescentColors randColor = new DescentColors();
HTTPConnectionThreadToPopulateMap(String... params) {
url = params[0];
parametersToPass = new String[params.length-1];
for(int i=1; i<params.length; i++) {
parametersToPass[i-1] = params[i];
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progress.setMessage("Please wait");
progress.show();
}
@Override
protected String doInBackground(Void... params) {
ems.storeLogs("HTTP request created");
String httpResponse = httpConnection.HTTPexecute(url, parametersToPa
ss);
return httpResponse;
}
@Override
protected void onPostExecute(String httpResponse) {
super.onPostExecute(httpResponse);
progress.dismiss();

if(httpResponse!=null) {
ems.storeLogs("HTTP request returned:\t" + httpResponse);
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInsta
nce();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(httpRespon
se));
Document dom = db.parse(is);
boolean isFirst = true;
LinearLayout legendLayout = (LinearLayout) findViewById(R.id
.contentLegend);
legendLayout.removeAllViews();
mMap.clear();
String status = HTTPConnection.parseXMLusingXpath(dom, "/xml
/body/status");
if (status.equals("Success")) {
((DrawerLayout) findViewById(R.id.drawer_layout)).closeD
rawers();
NodeList nl = dom.getElementsByTagName("locationDetails"
);
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
if (nl.item(i).getNodeType() == Node.ELEMENT_NOD
E) {
Element el = (Element) nl.item(i);
if (el.getNodeName().contains("locationDetai
ls")) {
String locId = el.getElementsByTagName("
locId").item(0).getTextContent();
String locLatitude = el.getElementsByTag
Name("locLatitude").item(0).getTextContent();
String locLongitude = el.getElementsByTa
gName("locLongitude").item(0).getTextContent();
String locAccuracy = el.getElementsByTag
Name("locAccuracy").item(0).getTextContent();
String locRecordedTime = el.getElementsB
yTagName("locRecordedTime").item(0).getTextContent();
//String locUpdateType = el.getElementsB
yTagName("locUpdateType").item(0).getTextContent();
Location tempLoc = new Location(Integer.
parseInt(locId), Double.parseDouble(locLatitude), Double.parseDouble(locLongitud
e), Double.parseDouble(locAccuracy), sdfSQL.parse(locRecordedTime));
Location filteredLoc = checkJunk(tempLoc
);
if(filteredLoc!=null) {
Location bulkFilter = checkBulk(filt
eredLoc);
if(bulkFilter!=null) {
if(isFirst) {
plotMarker(bulkFilter, 1);
isFirst = false;

} else {
plotMarker(bulkFilter, 0);
}
}
}
}
}
}
resolveBuffers();
mMap.addPolyline(pathPolyLine);
LatLngBounds bounds = builder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBound
s(bounds, 100);
mMap.animateCamera(cu);
TextView totalDistTextView = (TextView) findViewById
(R.id.distInTrip);
p:

totalDistTextView.setText("Distance travelled in Tri


"+(totalDistance/1000) + " kms");
}
} else {
ems.handleError(2,null,dom);
}
} catch (ParserConfigurationException e) {
ems.handleError(1,e, null);
} catch (SAXException e) {
ems.handleError(1, e, null);
} catch (IOException e) {
ems.handleError(1, e, null);
} catch (XPathExpressionException e) {
ems.handleError(1,e,null);
} catch (ParseException e) {
ems.handleError(1, e, null);
}
}
}
private Location checkJunk(Location point) {
if(junkBuffer[0]==null) {
junkBuffer[0]=point;
return point;
} else if(junkBuffer[1]==null) {
junkBuffer[1]=point;
return null;
} else if(junkBuffer[2]==null) {
junkBuffer[2]=point;
return null;
} else {
double x = Location.getDistance(junkBuffer[0], junkBuffer[1]);
double y = Location.getDistance(junkBuffer[1], junkBuffer[2]);
if(((x+y)/2) > junkThreshold) {
junkBuffer[1] = junkBuffer[2];
junkBuffer[2] = point;
return null;
} else {
junkBuffer[0] = junkBuffer[1];
junkBuffer[1] = junkBuffer[2];
junkBuffer[2] = point;
return junkBuffer[0];

}
}
}
private Location checkBulk(Location point) {
if(bulkBuffer[0]==null) {
bulkBuffer[0]=point;
return null;
} else if(bulkBuffer[1]==null) {
bulkBuffer[1]=point;
return null;
} else {
double d = Location.getDistance(bulkBuffer[0], bulkBuffer[1]);
if(d > bulkThreshold) {
Location temp = bulkBuffer[0];
bulkBuffer[0] = bulkBuffer[1];
bulkBuffer[1] = point;
temp.setLocTimeEnd(bulkBuffer[0].getLocStartTime());
return temp;
} else {
bulkBuffer[0] = Location.calculateCentroid(bulkBuffer[0], bu
lkBuffer[1]);
bulkBuffer[1] = point;
return null;
}
}
}
private void resolveBuffers() {
if((junkBuffer[2]==null)&&(junkBuffer[1]==null)) {
junkBuffer[0].setLocTimeEnd(junkBuffer[0].getLocStartTime());
plotMarker(junkBuffer[0], 2);
return;
} else if(junkBuffer[2]==null) {
junkBuffer[0].setLocTimeEnd(junkBuffer[1].getLocStartTime());
junkBuffer[1].setLocTimeEnd(junkBuffer[1].getLocStartTime());
plotMarker(junkBuffer[0], 1);
plotMarker(junkBuffer[1], 2);
return;
}
double x = Location.getDistance(junkBuffer[0], junkBuffer[1]);
double y = Location.getDistance(junkBuffer[1], junkBuffer[2]);
if(((x+y)/2) > junkThreshold) {
junkBuffer[1] = junkBuffer[2];
junkBuffer[2] = null;
} else {
junkBuffer[0] = junkBuffer[1];
junkBuffer[1] = junkBuffer[2];
junkBuffer[2] = null;
Location filterBulk = checkBulk(junkBuffer[0]);
if(filterBulk!=null) {
plotMarker(filterBulk, 0);
}
}
x = Location.getDistance(junkBuffer[0], junkBuffer[1]);
if(x<junkThreshold) {

Location filterBulk = checkBulk(junkBuffer[1]);


if(filterBulk!=null) {
plotMarker(filterBulk, 0);
}
}
double d = Location.getDistance(bulkBuffer[0], bulkBuffer[1]);
if(d > bulkThreshold) {
Location temp = bulkBuffer[0];
bulkBuffer[0] = bulkBuffer[1];
bulkBuffer[1] = null;
temp.setLocTimeEnd(bulkBuffer[0].getLocStartTime());
plotMarker(temp, 0);
} else {
bulkBuffer[0] = Location.calculateCentroid(bulkBuffer[0], bulkBu
ffer[1]);
bulkBuffer[1] = null;
}
bulkBuffer[0].setLocTimeEnd(bulkBuffer[0].getLocStartTime());
plotMarker(bulkBuffer[0], 2);
}
private void addToLegend(int toMarkerId, int polylineColor, int currLege
ndId) {
LinearLayout singleLegend = new LinearLayout(Dashboard.this);
singleLegend.setOrientation(LinearLayout.HORIZONTAL);
singleLegend.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup
.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
singleLegend.setGravity(Gravity.CENTER);
ImageView from = new ImageView(Dashboard.this);
from.setImageBitmap(writeTextOnDrawable(R.drawable.stop_marker, (toM
arkerId-1)+""));
Button color = new Button(Dashboard.this);
color.setBackgroundColor(polylineColor);
color.setTextColor(Color.WHITE);
color.setText("
Marker-1
to
Marker-2
");
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Vie
wGroup.LayoutParams.WRAP_CONTENT, 120);
params.setMargins(50,10,50,10);
color.setLayoutParams(params);
color.setId(currLegendId);
color.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
showSinglePath(v.getId());
}
}
);
ImageView to = new ImageView(Dashboard.this);
to.setImageBitmap(writeTextOnDrawable(R.drawable.stop_marker, (toMar
kerId+"")));
singleLegend.addView(from);

singleLegend.addView(color);
singleLegend.addView(to);
LinearLayout slidingPanel = (LinearLayout) findViewById(R.id.content
Legend);
slidingPanel.addView(singleLegend);
}
private void showSinglePath(int currPathId) {
mMap.clear();
PolylineOptions currPolyLine = polylineMap.get(currPathId);
LatLng firstPoint = currPolyLine.getPoints().get(0);
for(LatLng curr:currPolyLine.getPoints()) {
mMap.addMarker(new MarkerOptions().position(curr).icon(BitmapDes
criptorFactory.fromResource(R.drawable.path_icon)));
}
LatLng lastPoint = currPolyLine.getPoints().get(currPolyLine.getPoin
ts().size()-1);
mMap.addPolyline(currPolyLine);
BitmapDescriptor flagBitmapDescriptorFirst = BitmapDescriptorFactory
.fromBitmap(writeTextOnDrawable(R.drawable.stop_marker, markerMap.get(currPathId
-1) + ""));
mMap.addMarker(new MarkerOptions().position(firstPoint).icon(flagBit
mapDescriptorFirst));
BitmapDescriptor flagBitmapDescriptorLast = BitmapDescriptorFactory.
fromBitmap(writeTextOnDrawable(R.drawable.stop_marker, markerMap.get(currPathId)
+ ""));
mMap.addMarker(new MarkerOptions().position(lastPoint).icon(flagBitm
apDescriptorLast));
SlidingUpPanelLayout slidingPanel = (SlidingUpPanelLayout) findViewB
yId(R.id.sliding_layout);
slidingPanel.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED
);
}
private void plotMarker(Location location, int isMarker) {
LatLng latLng = new LatLng(location.getLocLatitude(), location.getLo
cLongitude());
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
if ((location.getLocEndTime().getTime() - location.getLocStartTime()
.getTime() >= 10*60*1000)||(isMarker>=1)) {
if(isMarker!=1) {
//if(pathPolyLine!=null) {
polylineMap.put(legendId, pathPolyLine);
markerMap.put(legendId, markerCount);
mMap.addPolyline(pathPolyLine);
if (markerCount != 1) {
addToLegend(markerCount, randColor.getDescentColor(m
arkerCount), legendId);
totalDistance += Location.getDistance(location, prev
Loc);
//System.out.println(location.getLocId() + " to " +
prevLoc.getLocId());
}
prevLoc = location;
legendId++;
//}

BitmapDescriptor flagBitmapDescriptor = BitmapDescriptorFact


ory.fromBitmap(writeTextOnDrawable(R.drawable.stop_marker, markerCount + ""));
if(location.getLocUpdateType()==1) {
mMap.addMarker(new MarkerOptions().position(latLng).icon
(flagBitmapDescriptor).title(sdf.format(location.getLocStartTime()) + " to " + s
df.format(location.getLocStartTime())));
} else {
mMap.addMarker(new MarkerOptions().position(latLng).icon
(flagBitmapDescriptor).title(sdf.format(location.getLocStartTime()) + " to " + s
df.format(location.getLocEndTime())));
}
markerCount++;
}
pathPolyLine = new PolylineOptions();
pathPolyLine.width(10);
pathPolyLine.color(randColor.getDescentColor(markerCount));
} else {
if(markerCount!=1) {
totalDistance += Location.getDistance(location, prevLoc);
}
prevLoc = location;
if(location.getLocUpdateType()==1) {
mMap.addMarker(new MarkerOptions().position(latLng).icon(Bit
mapDescriptorFactory.fromResource(R.drawable.path_icon)).title(sdf.format(locati
on.getLocStartTime()) + " to " + sdf.format(location.getLocStartTime())));
} else {
mMap.addMarker(new MarkerOptions().position(latLng).icon(Bit
mapDescriptorFactory.fromResource(R.drawable.path_icon)).title(sdf.format(locati
on.getLocStartTime()) + " to " + sdf.format(location.getLocEndTime())));
}
}
pathPolyLine.add(latLng);
builder.include(latLng);
}
private Bitmap writeTextOnDrawable(int drawableId, String text) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId)
.copy(Bitmap.Config.ARGB_8888, true);
Typeface tf = Typeface.create("Helvetica", Typeface.BOLD);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setTypeface(tf);
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(convertToPixels(15));
Rect textRect = new Rect();
paint.getTextBounds(text, 0, text.length(), textRect);
Canvas canvas = new Canvas(bm);
//If the text is bigger than the canvas , reduce the font size
if(textRect.width() >= (canvas.getWidth() - 4))
//the padding on
either sides is considered as 4, so as to appropriately fit in the text
paint.setTextSize(convertToPixels(15));
//Scaling needs t

o be used for different dpi's


//Calculate the positions
int xPos = (canvas.getWidth() / 2);
position offset

//-2 is for regulating the x

//"- ((paint.descent() + paint.ascent()) / 2)" is the distance from


the baseline to the center.
int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + pai
nt.ascent()) / 2)) ;
canvas.drawText(text, xPos, yPos-10, paint);
return bm;
}
public int convertToPixels(int nDP)
{
final float conversionScale = Dashboard.this.getResources().getDispl
ayMetrics().density;
return (int) ((nDP * conversionScale) + 0.5f) ;
}
}

Potrebbero piacerti anche