Person Track with DayWise Report

Xml Files:-

trackingggg.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />

    <LinearLayout
        android:id="@+id/traffic"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_gravity="center"
        android:layout_marginBottom="20dp"
        android:layout_marginRight="10dp"
        android:background="@drawable/maptransparent"
        android:gravity="center"
        android:orientation="vertical" >

        <Button
            android:id="@+id/button1"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:text="0 KM"
            android:textSize="13dp"
            android:textColor="#fff"
            android:background="@null"
            android:textStyle="bold" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/trsaffic"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignLeft="@+id/traffic"
        android:layout_alignParentTop="true"
        android:layout_marginTop="10dp"
        android:background="@null"
        android:orientation="vertical" >

        <ProgressBar
            android:id="@+id/progressbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:indeterminateDrawable="@drawable/progressbackground1"
            android:visibility="invisible" />
    </LinearLayout>

</RelativeLayout>

onedaylayout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />

    <LinearLayout
        android:id="@+id/traffic"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_gravity="center"
        android:layout_marginBottom="20dp"
        android:layout_marginRight="10dp"
        android:background="@drawable/round_button"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="invisible" >

        <Button
            android:id="@+id/button1"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:background="@drawable/sendtick" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/trsaffic"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignLeft="@+id/traffic"
        android:layout_alignParentTop="true"
        android:layout_marginTop="10dp"
        android:background="@null"
        android:orientation="vertical" >

        <ProgressBar
            android:id="@+id/progressbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:indeterminateDrawable="@drawable/progressbackground1"
            android:visibility="invisible" />
    </LinearLayout>


</RelativeLayout>

Java Files:-

ManiActivityTrack.java
package com.parthivpersiontracking.inn;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class ManiActivityTrack extends Activity {

String[] latitude, longitude, busidfordelete;
String[] busno;
int count = 0;
Button traffic;
String urlJsonArry;
String[] repstatus;
Handler mHandler = new Handler();
private int day;
private int month;
private int year;
Boolean isInternetPresent = false;
LatLngBounds.Builder builder;
private ProgressDialog mProgressDialog;
final int RQS_GooglePlayServices = 1;
MapFragment myMapFragment;
String deletethisuser = "0";
GoogleMap myMap;
int totallength = 0;
private String jsonResponse;
int on = 0;
private Calendar cal;
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
Typeface tf;
String fontPath = "fonts/Smoolthan Bold.otf";
String datetoserver;
private final long startTime = 10 * 1000;
private final long interval = 1 * 1000;
ProgressBar load;
double tokm, str;
int ct = 0;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
overridePendingTransition(R.anim.move_left_in_activity,
R.anim.move_left_out_activity);
setContentView(R.layout.trackingggg);
tf = Typeface.createFromAsset(getAssets(), fontPath);
traffic = (Button) findViewById(R.id.button1);

cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);

isInternetPresent = isConnectingToInternet();
if (isInternetPresent) {

} else {

Context context = getApplicationContext();
LayoutInflater inflater = getLayoutInflater();
View customToastroot = inflater
.inflate(R.layout.fillallfield, null);
TextView validate = (TextView) customToastroot
.findViewById(R.id.textView1);
validate.setText("INTERNET CONNECTION SLOW?");
validate.setTypeface(tf);

Toast customtoast = new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM, 0, 0);
customtoast.setDuration(1000);
customtoast.show();

finish();
}

load = (ProgressBar) findViewById(R.id.progressbar);
traffic.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (on == 2) {

int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
traffic.setBackgroundDrawable(getResources()
.getDrawable(R.drawable.trafficred));
} else {
traffic.setBackground(getResources().getDrawable(
R.drawable.trafficred));
}
myMap.setTrafficEnabled(true);
on = 1;
} else if (on == 1) {

int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
traffic.setBackgroundDrawable(getResources()
.getDrawable(R.drawable.trafficneww));
} else {
traffic.setBackground(getResources().getDrawable(
R.drawable.trafficneww));
}
myMap.setTrafficEnabled(false);
on = 2;
} else {
Context context = getApplicationContext();
LayoutInflater inflater = getLayoutInflater();
View customToastroot = inflater.inflate(
R.layout.fillallfield, null);
TextView validate = (TextView) customToastroot
.findViewById(R.id.textView1);
validate.setText("Please wait till the map load...");
validate.setTypeface(tf);
validate.setTextColor(Color.BLACK);
Toast customtoast = new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM, 0,
0);
customtoast.setDuration(1000);
customtoast.show();
}

}
});
try {
new retrievetr().execute("");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

@Override
protected void onResume() {
super.onResume();

int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS) {
/*
* Toast.makeText(getApplicationContext(),
* "isGooglePlayServicesAvailable SUCCESS",
* Toast.LENGTH_LONG).show();
*/
} else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
RQS_GooglePlayServices);
}
}

class retrievetr extends AsyncTask<String, String, String> {
@SuppressWarnings("deprecation")
protected void onPreExecute() {
super.onPreExecute();

try {
load.setVisibility(View.VISIBLE);
} catch (Exception e) {
// TODO Auto-generated catch block
load.setVisibility(View.VISIBLE);
e.printStackTrace();
}

}

protected String doInBackground(String... params) {

try {
totallength = 0;

urlJsonArry = "http://geo.seppro.net/trasckimhsa/listofplacesinmap.php?companyname=parthiv";
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

try {
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
try {
try {
jsonResponse = "";
totallength = response.length();
busidfordelete = new String[response
.length()];
latitude = new String[response.length()];
longitude = new String[response
.length()];
busno = new String[response.length()];
repstatus = new String[response
.length()];
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

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

JSONObject person = (JSONObject) response
.get(i);

String date = new SimpleDateFormat(
"yyyy-MM-dd")
.format(new Date());

if (date.equals(person
.getString("lastdate"))) {

Calendar c = Calendar.getInstance();
int hour = c
.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
String jointime = hour + "" + min;
String str1 = person
.getString("lasttime");
String str = str1.replace(":", "");

int servertime = Integer
.parseInt(str);
int currenttime = Integer
.parseInt(jointime);

int minus = currenttime
- servertime;

if (minus >= 10) {
try {

repstatus[i] = "1";
latitude[i] = person
.getString("rep_lat");
longitude[i] = person
.getString("rep_long");
busno[i] = person
.getString("rep_name");
busidfordelete[i] = person
.getString("rep_id");
} catch (Exception e) {
// TODO Auto-generated catch
// block
e.printStackTrace();
}
} else {

try {
repstatus[i] = person
.getString("repcurrentstatus");
latitude[i] = person
.getString("rep_lat");
longitude[i] = person
.getString("rep_long");
busno[i] = person
.getString("rep_name");
busidfordelete[i] = person
.getString("rep_id");
} catch (Exception e) {
// TODO Auto-generated catch
// block
e.printStackTrace();
}
}

} else {

if (person.getString("rep_lat")
.contains(".")) {
try {
repstatus[i] = "1";
latitude[i] = person
.getString("rep_lat");
longitude[i] = person
.getString("rep_long");
busno[i] = person
.getString("rep_name");
busidfordelete[i] = person
.getString("rep_id");
} catch (Exception e) {
// TODO Auto-generated catch
// block
e.printStackTrace();
}
} else {

try {
repstatus[i] = "1";
latitude[i] = "13.0867769";
longitude[i] = "80.2143539";
busno[i] = person
.getString("rep_name");
busidfordelete[i] = person
.getString("rep_id");
} catch (Exception e) {
// TODO Auto-generated catch
// block
e.printStackTrace();
}

}

}

}

try {
ShowAllContent();
load.setVisibility(View.INVISIBLE);
} catch (Exception e) {
// TODO Auto-generated catch block
load.setVisibility(View.INVISIBLE);
e.printStackTrace();
}
} catch (JSONException e) {
Context context = getApplicationContext();
LayoutInflater inflater = getLayoutInflater();
View customToastroot = inflater.inflate(
R.layout.fillallfield, null);
TextView validate = (TextView) customToastroot
.findViewById(R.id.textView1);
validate.setText("Internet connection is to slow...");
validate.setTypeface(tf);
validate.setTextColor(Color.BLACK);
Toast customtoast = new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM
| Gravity.BOTTOM, 0, 0);
customtoast.setDuration(1000);
customtoast.show();

load.setVisibility(View.INVISIBLE);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

Context context = getApplicationContext();
LayoutInflater inflater = getLayoutInflater();
View customToastroot = inflater.inflate(
R.layout.fillallfield, null);
TextView validate = (TextView) customToastroot
.findViewById(R.id.textView1);
validate.setText("Internet connection is to slow...");
validate.setTypeface(tf);
validate.setTextColor(Color.BLACK);
Toast customtoast = new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM
| Gravity.BOTTOM, 0, 0);
customtoast.setDuration(1000);
customtoast.show();
load.setVisibility(View.INVISIBLE);

}
});

AppController.getInstance().addToRequestQueue(req);
} catch (Exception e) {
System.out.println("Exception : " + e.getMessage());
if (count == 0) {

Context context = getApplicationContext();
LayoutInflater inflater = getLayoutInflater();
View customToastroot = inflater.inflate(
R.layout.fillallfield, null);
TextView validate = (TextView) customToastroot
.findViewById(R.id.textView1);
validate.setText("Internet connection is to slow...");
validate.setTypeface(tf);
validate.setTextColor(Color.BLACK);
Toast customtoast = new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM, 0,
0);
customtoast.setDuration(1000);
customtoast.show();
load.setVisibility(View.INVISIBLE);

}
}

return null;
}

private void ShowAllContent() {
try {
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment = (MapFragment) myFragmentManager
.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// myMap.setTrafficEnabled(true);

myMap.clear();

try {

builder = new LatLngBounds.Builder();
for (int i = 0; i < totallength; i++) {

Double lat = Double.parseDouble(latitude[i]);
Double lon = Double.parseDouble(longitude[i]);
LatLng Leicester_Square;

if (lat == 0.0) {

Leicester_Square = new LatLng(13.0867769, 80.2143539);

View marker = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.custom_marker_layout, null);
ImageView im = (ImageView) marker.findViewById(R.id.im);
im.setBackgroundDrawable(getResources().getDrawable(
R.drawable.signalost));

TextView numTxt = (TextView) marker
.findViewById(R.id.num_txt);
TextView idfordelete = (TextView) marker
.findViewById(R.id.idfordelete);
numTxt.setText("" + busno[i]);
idfordelete.setText("" + busidfordelete[i]);
numTxt.setTypeface(tf);

myMap.addMarker(new MarkerOptions()
.position(Leicester_Square)
.title("" + busidfordelete[i])
.icon(BitmapDescriptorFactory
.fromBitmap(createDrawableFromView(
ManiActivityTrack.this, marker))));
builder.include(Leicester_Square);

} else {

if (repstatus[i].equals("1")) {
Leicester_Square = new LatLng(lat, lon);

View marker = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.custom_marker_layout,
null);
ImageView im = (ImageView) marker
.findViewById(R.id.im);
// im.setBackgroundDrawable(
// getResources().getDrawable(R.drawable.redalertperson)
// );
im.setBackgroundDrawable(getResources()
.getDrawable(R.drawable.activerep));
TextView numTxt = (TextView) marker
.findViewById(R.id.num_txt);
TextView idfordelete = (TextView) marker
.findViewById(R.id.idfordelete);
numTxt.setText("" + busno[i]);
idfordelete.setText("" + busidfordelete[i]);
numTxt.setTypeface(tf);

myMap.addMarker(new MarkerOptions()
.position(Leicester_Square)
.title("" + busidfordelete[i])
.icon(BitmapDescriptorFactory
.fromBitmap(createDrawableFromView(
ManiActivityTrack.this,
marker))));
builder.include(Leicester_Square);
} else if (repstatus[i].equals("2")) {
Leicester_Square = new LatLng(lat, lon);

View marker = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.custom_marker_layout,
null);
ImageView im = (ImageView) marker
.findViewById(R.id.im);
// im.setBackgroundDrawable(
// getResources().getDrawable(R.drawable.waitingfor)
// );
im.setBackgroundDrawable(getResources()
.getDrawable(R.drawable.activerep));
TextView numTxt = (TextView) marker
.findViewById(R.id.num_txt);
TextView idfordelete = (TextView) marker
.findViewById(R.id.idfordelete);
numTxt.setText("" + busno[i]);
idfordelete.setText("" + busidfordelete[i]);
numTxt.setTypeface(tf);

myMap.addMarker(new MarkerOptions()
.position(Leicester_Square)
.title("" + busidfordelete[i])
.icon(BitmapDescriptorFactory
.fromBitmap(createDrawableFromView(
ManiActivityTrack.this,
marker))));
builder.include(Leicester_Square);
} else {
Leicester_Square = new LatLng(lat, lon);

View marker = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.custom_marker_layout,
null);
ImageView im = (ImageView) marker
.findViewById(R.id.im);

im.setBackgroundDrawable(getResources()
.getDrawable(R.drawable.activerep));
TextView numTxt = (TextView) marker
.findViewById(R.id.num_txt);
TextView idfordelete = (TextView) marker
.findViewById(R.id.idfordelete);
numTxt.setText("" + busno[i]);
idfordelete.setText("" + busidfordelete[i]);
numTxt.setTypeface(tf);

myMap.addMarker(new MarkerOptions()
.position(Leicester_Square)
.title("" + busidfordelete[i])
.icon(BitmapDescriptorFactory
.fromBitmap(createDrawableFromView(
ManiActivityTrack.this,
marker))));
builder.include(Leicester_Square);
}

}

}
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

try {
// myMap.getUiSettings().setMapToolbarEnabled(false);
LatLngBounds bounds = builder.build();
myMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds,
16));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

try {
on = 2;
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

myMap.setInfoWindowAdapter(new InfoWindowAdapter() {

// Use default InfoWindow frame
@Override
public View getInfoWindow(Marker args) {
return null;
}

// Defines the contents of the InfoWindow
@Override
public View getInfoContents(final Marker args) {

// Getting view from the layout file info_window_layout
View v = getLayoutInflater().inflate(R.layout.newproblem,
null);

TextView yes = (TextView) v.findViewById(R.id.yes);
yes.setTypeface(tf);

myMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
public void onInfoWindowClick(Marker marker) {
// Toast.makeText(getApplicationContext(),
// "ci"+args.getTitle(), 1000).show();

deletethisuser = "" + args.getTitle();

final Dialog viewdialog1 = new Dialog(
ManiActivityTrack.this);
viewdialog1
.requestWindowFeature(Window.FEATURE_NO_TITLE);

viewdialog1
.getWindow()
.setBackgroundDrawable(
new ColorDrawable(
android.graphics.Color.TRANSPARENT));
viewdialog1
.setContentView(R.layout.confirmationbox);
viewdialog1.setCancelable(true);
viewdialog1.setCanceledOnTouchOutside(true);
TextView heading = (TextView) viewdialog1
.findViewById(R.id.heading);
heading.setTypeface(tf);
TextView title = (TextView) viewdialog1
.findViewById(R.id.title);

Button yes = (Button) viewdialog1
.findViewById(R.id.ok);

Button no = (Button) viewdialog1
.findViewById(R.id.close);

yes.setTypeface(tf);
no.setTypeface(tf);

title.setTypeface(tf);
title.setText("Are you sure?");

yes.setOnClickListener(new OnClickListener() {

@SuppressWarnings("deprecation")
@Override
public void onClick(View v) {

viewdialog1.dismiss();

showDialog(0);

}
});

no.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

viewdialog1.dismiss();
}
});

viewdialog1.show();

}
});

// Returning the view containing InfoWindow contents
return v;

}
});

int m = 0;
tokm = 0.0;
str = 0.0;
for (int t = 0; t < ct; t++) {

System.out.println("test--2----" + ct);
m = (t + 1);
if (m == ct) {
System.out.println("test--m----" + m);
} else {

int Radius = 6371;// radius of earth in Km
double lat1 = Double.parseDouble(latitude[t]);
double lat2 = Double.parseDouble(latitude[m]);
double lon1 = Double.parseDouble(longitude[t]);
double lon2 = Double.parseDouble(longitude[m]);
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2))
* Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
double valueResult = Radius * c;
double km = valueResult / 1;
DecimalFormat newFormat = new DecimalFormat("####");
int kmInDec = Integer.valueOf(newFormat.format(km));
double meter = valueResult % 1000;
int meterInDec = Integer.valueOf(newFormat.format(meter));

str = valueResult;

System.out.println("tokm--21----" + str);
if (str >= 5 && str <= 15) {
str = (str + 2);
} else if (str > 15 && str <= 30) {
str = (str + 5);
} else if (str > 30 && str <= 60) {
str = (str + 10);
} else if (str > 60 && str <= 100) {
str = (str + 20);
} else {
str = str;
}

tokm = (tokm + str);

}

}
String result = String.format("%.2f", tokm);
traffic.setText(result + " KM");

}

}

public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}

}
return false;
}

public static Bitmap createDrawableFromView(Context context, View view) {
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay()
.getMetrics(displayMetrics);
view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
view.layout(0, 0, displayMetrics.widthPixels,
displayMetrics.heightPixels);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(),
view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

Canvas canvas = new Canvas(bitmap);
view.draw(canvas);

return bitmap;
}

protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(ManiActivityTrack.this, datePickerListener,
year, month, day);
}

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
if ((selectedMonth + 1) < 10 && selectedDay < 10) {

datetoserver = selectedYear + "/0" + (selectedMonth + 1) + "/0"
+ selectedDay;

SharedPreferences pref1 = getApplicationContext()
.getSharedPreferences("repdate", MODE_PRIVATE);
Editor editor1 = pref1.edit();
editor1.putString("repdatee", datetoserver); // Saving string
editor1.commit();

SharedPreferences pref = getApplicationContext()
.getSharedPreferences("reptrack", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("repimei", deletethisuser); // Saving string
editor.commit(); // commit changes
Intent in = new Intent(ManiActivityTrack.this,
ReportDateWise.class);
startActivity(in);

} else if ((selectedMonth + 1) < 10) {

datetoserver = selectedYear + "/0" + (selectedMonth + 1) + "/"
+ selectedDay;

SharedPreferences pref1 = getApplicationContext()
.getSharedPreferences("repdate", MODE_PRIVATE);
Editor editor1 = pref1.edit();
editor1.putString("repdatee", datetoserver); // Saving string
editor1.commit();

SharedPreferences pref = getApplicationContext()
.getSharedPreferences("reptrack", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("repimei", deletethisuser); // Saving string
editor.commit(); // commit changes
Intent in = new Intent(ManiActivityTrack.this,
ReportDateWise.class);
startActivity(in);

} else if (selectedDay < 10) {
datetoserver = selectedYear + "/" + (selectedMonth + 1) + "/0"
+ selectedDay;

SharedPreferences pref1 = getApplicationContext()
.getSharedPreferences("repdate", MODE_PRIVATE);
Editor editor1 = pref1.edit();
editor1.putString("repdatee", datetoserver); // Saving string
editor1.commit();

SharedPreferences pref = getApplicationContext()
.getSharedPreferences("reptrack", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("repimei", deletethisuser); // Saving string
editor.commit(); // commit changes
Intent in = new Intent(ManiActivityTrack.this,
ReportDateWise.class);
startActivity(in);

} else {

datetoserver = selectedYear + "/" + (selectedMonth + 1) + "/"
+ selectedDay;

SharedPreferences pref1 = getApplicationContext()
.getSharedPreferences("repdate", MODE_PRIVATE);
Editor editor1 = pref1.edit();
editor1.putString("repdatee", datetoserver); // Saving string
editor1.commit();

SharedPreferences pref = getApplicationContext()
.getSharedPreferences("reptrack", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("repimei", deletethisuser); // Saving string
editor.commit(); // commit changes
Intent in = new Intent(ManiActivityTrack.this,
ReportDateWise.class);
startActivity(in);

}

}
};

}

ReportDateWise.java

package com.parthivpersiontracking.inn;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.FragmentActivity;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN) public class ReportDateWise extends Activity  {

String [] latitude,longitude;
String[] busno;
int count=0;
Button traffic;

Handler mHandler = new Handler();

String splitlat;
LatLngBounds.Builder builder;
 private ProgressDialog mProgressDialog;
 final int RQS_GooglePlayServices = 1;
 MapFragment myMapFragment;
 GoogleMap myMap ;
 int totallength=0;
 private String jsonResponse;
 int on=0;

 private CountDownTimer countDownTimer;
 private boolean timerHasStarted = false;
 Typeface tf;
String fontPath = "fonts/Smoolthan Bold.otf";
LatLng origin;
    LatLng dest;
 
 private final long startTime = 10 * 1000;
 private final long interval = 1 * 1000;
 ProgressBar load;
 Polyline line;
 String address,city,state,country,postalCode,knownName;
 @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  this.requestWindowFeature(Window.FEATURE_NO_TITLE);
  overridePendingTransition(R.anim.move_left_in_activity, R.anim.move_left_out_activity);
  setContentView(R.layout.onedaylayout);
  tf= Typeface.createFromAsset(getAssets(),
fontPath);
  traffic=(Button)findViewById(R.id.button1);



  load=(ProgressBar)findViewById(R.id.progressbar);
  traffic.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Intent in =new Intent(onedyreport.this,custnewpincodepincode1bulksmsstudenteventsview.class);
//startActivity(in);



}
});


  new retrievetr().execute("");



 }




 @Override
 protected void onResume() {
  super.onResume();

  int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
  if (resultCode == ConnectionResult.SUCCESS)
  {
   /*Toast.makeText(getApplicationContext(),
     "isGooglePlayServicesAvailable SUCCESS",
     Toast.LENGTH_LONG).show(); */
  }
  else
  {
   GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
  }
 }




class retrievetr extends AsyncTask<String, String, String> {
@SuppressWarnings("deprecation")
protected void onPreExecute() {
super.onPreExecute();

load.setVisibility(View.VISIBLE);

}

protected String doInBackground(String... params) {

totallength=0;





  SharedPreferences pref = getApplicationContext().getSharedPreferences("repdate", MODE_PRIVATE);

  SharedPreferences pref1 = getApplicationContext().getSharedPreferences("reptrack", MODE_PRIVATE);



String urlJsonArry ="PASTE YOUR URL";

try {
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
public void onResponse(JSONArray response) {
try
{
jsonResponse = "";
totallength=response.length();

latitude=new String[response.length()];
longitude=new String[response.length()];
busno=new String[response.length()];


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

JSONObject person = (JSONObject) response
.get(i);

splitlat=person.getString("name");

if(splitlat.length()<3)
{

}
else
{
String[] animalsArray = splitlat.split(",");

latitude[i]=animalsArray[0];
longitude[i]=animalsArray[1];
busno[i]=person.getString("time");

Double lla=Double.parseDouble(""+latitude[i]);
Double llo=Double.parseDouble(""+longitude[i]);




}

                     
}

if(totallength==0)
{

   Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
    TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);    
validate.setText("Sorry no details available...");
validate.setTypeface(tf);
validate.setTextColor(Color.WHITE);
Toast customtoast=new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
customtoast.setDuration(1000);
customtoast.show();

   load.setVisibility(View.INVISIBLE);

}
else
{

if(splitlat.length()<3)
{

   Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
    TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);    
validate.setText("Sorry no details available...");
validate.setTypeface(tf);
validate.setTextSize(16);
validate.setTextColor(Color.WHITE);
Toast customtoast=new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
customtoast.setDuration(1000);
customtoast.show();



}
else
{
ShowAllContent();
}

load.setVisibility(View.INVISIBLE);
}


}
   catch (JSONException e)
       {
   Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
    TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);    
validate.setText("Internet connection is to slow...");
validate.setTypeface(tf);
validate.setTextColor(Color.BLACK);
Toast customtoast=new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
customtoast.setDuration(1000);
customtoast.show();

   load.setVisibility(View.INVISIBLE);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {


   Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
    TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);    
validate.setText("Internet connection is to slow...");
validate.setTypeface(tf);
validate.setTextColor(Color.BLACK);
Toast customtoast=new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
customtoast.setDuration(1000);
customtoast.show();

   load.setVisibility(View.INVISIBLE);


}
});

AppController.getInstance().addToRequestQueue(req);
}
catch (Exception e)
{
System.out.println("Exception : " + e.getMessage());
if(count==0)
{

   Context context=getApplicationContext();
LayoutInflater inflater=getLayoutInflater();
View customToastroot =inflater.inflate(R.layout.fillallfield, null);
    TextView validate=(TextView)customToastroot.findViewById(R.id.textView1);    
validate.setText("Internet connection is to slow...");
validate.setTypeface(tf);
validate.setTextColor(Color.BLACK);
Toast customtoast=new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.BOTTOM | Gravity.BOTTOM,0, 0);
customtoast.setDuration(1000);
customtoast.show();

   load.setVisibility(View.INVISIBLE);

}
}

return null;
}



private void ShowAllContent()
{


  try {
try {
FragmentManager myFragmentManager = getFragmentManager();
  MapFragment myMapFragment =
    (MapFragment)myFragmentManager.findFragmentById(R.id.map);
  myMap = myMapFragment.getMap();
  myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// myMap.setTrafficEnabled(true);



try {
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.busmarker);
  BitmapDescriptor start = BitmapDescriptorFactory.fromResource(R.drawable.startmap);
  BitmapDescriptor endpo = BitmapDescriptorFactory.fromResource(R.drawable.endpoin);
  builder = new LatLngBounds.Builder();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

  int endpoin=totallength-1;
  BitmapDescriptor icon1;
  for (int i = 0; i < totallength; i++)
{
  Double lat=Double.parseDouble(latitude[i]);
  Double lon=Double.parseDouble(longitude[i]);






  LatLng Leicester_Square = new LatLng(lat, lon);
  int j=i+1;

  Double lat1=0.0;;
  Double lon1=0.0;
String co=""+j;
View marker = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.newmarkerlayout, null);

  if(i==endpoin)
    {
  ImageView im=(ImageView)marker.findViewById(R.id.im);

im.setBackgroundDrawable( getResources().getDrawable(R.drawable.bussta) );
  TextView numTxt = (TextView) marker.findViewById(R.id.num_txt);
TextView idfordelete = (TextView) marker.findViewById(R.id.idfordelete);
numTxt.setText("Rep is here");
idfordelete.setText("Rep is here");
numTxt.setTypeface(tf);
try {
myMap.addMarker(new MarkerOptions().position(Leicester_Square).title(lat+","+lon).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(ReportDateWise.this, marker))));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
builder.include(Leicester_Square);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    }
    else if(i==0)
    {
   
      lat1=Double.parseDouble(latitude[j]);
      lon1=Double.parseDouble(longitude[j]);
      /*line = myMap.addPolyline(new PolylineOptions()
            .add(new LatLng(lat, lon), new LatLng(lat1, lon1))
            .width(5)
            .color(Color.RED));*/
      ImageView im=(ImageView)marker.findViewById(R.id.im);

im.setBackgroundDrawable( getResources().getDrawable(R.drawable.startflagg) );
  TextView numTxt = (TextView) marker.findViewById(R.id.num_txt);
TextView idfordelete = (TextView) marker.findViewById(R.id.idfordelete);
numTxt.setText("Starting point");
idfordelete.setText("Starting point");
numTxt.setTypeface(tf);

try {
myMap.addMarker(new MarkerOptions().position(Leicester_Square).title(lat+","+lon).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(ReportDateWise.this, marker))));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
builder.include(Leicester_Square);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    }
    else
    {
   
   
   
    double  kmtr=0.0;

    lat1=Double.parseDouble(latitude[j]);
      lon1=Double.parseDouble(longitude[j]);
   
   
      double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat1-lat);
double dLng = Math.toRadians(lon1-lon);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat1)) *
            Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = (double) (earthRadius * c);
kmtr=dist+kmtr;


if(kmtr>100)
{
  /*line = myMap.addPolyline(new PolylineOptions()
            .add(new LatLng(lat, lon), new LatLng(lat1, lon1))
            .width(5)
            .color(Color.RED));*/
   
      ImageView im=(ImageView)marker.findViewById(R.id.im);

im.setBackgroundDrawable( getResources().getDrawable(R.drawable.locmark) );
  TextView numTxt = (TextView) marker.findViewById(R.id.num_txt);
TextView idfordelete = (TextView) marker.findViewById(R.id.idfordelete);
numTxt.setText(""+busno[i]);
idfordelete.setText(""+busno[i]);
numTxt.setTypeface(tf);

try {
myMap.addMarker(new MarkerOptions().position(Leicester_Square).title(lat+","+lon).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(ReportDateWise.this, marker))));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
builder.include(Leicester_Square);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

   
    }
 



}

  try {
//myMap.getUiSettings().setMapToolbarEnabled(false);
  LatLngBounds bounds = builder.build();

  myMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 17));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}


  try {
on=2;
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}




  try {
//new drawpath().execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}




  myMap.setInfoWindowAdapter(new InfoWindowAdapter() {

            // Use default InfoWindow frame
            @Override
            public View getInfoWindow(Marker args) {
                return null;
            }

            // Defines the contents of the InfoWindow
            @Override
            public View getInfoContents(final Marker args) {

                // Getting view from the layout file info_window_layout
            View v = getLayoutInflater().inflate(R.layout.newproblem, null);
         
            TextView yes = (TextView) v.findViewById(R.id.yes);
            yes.setTypeface(tf);
            yes.setText("Click to see full details?");

                myMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {       
                    public void onInfoWindowClick(Marker marker)
                    {
                   
                    // Toast.makeText(getApplicationContext(), args.getTitle(), 1000).show();
                   
                   
                   
                    String[] animalsArray = args.getTitle().split(",");
                   
                    Double polat=Double.parseDouble(""+animalsArray[0]);
                    Double poloc=Double.parseDouble(""+animalsArray[1]);
                   
                    try {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(ReportDateWise.this, Locale.getDefault());

addresses = geocoder.getFromLocation(polat, poloc, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5

if (addresses != null && addresses.size() > 0) {


address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
city = addresses.get(0).getLocality();
state = addresses.get(0).getAdminArea();
country = addresses.get(0).getCountryName();
postalCode = addresses.get(0).getPostalCode();
knownName = addresses.get(0).getFeatureName();

}

final Dialog viewdialog1 = new Dialog(ReportDateWise.this);
    viewdialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
   
    viewdialog1.getWindow().setBackgroundDrawable(
                   new ColorDrawable(
                   android.graphics.Color.TRANSPARENT));
    viewdialog1.setContentView(R.layout.addresspopup);
    viewdialog1.setCancelable(true);
    viewdialog1.setCanceledOnTouchOutside(true);
    final TextView busnos=(TextView)viewdialog1.findViewById(R.id.busno);
   
   
    busnos.setTypeface(tf);
    busnos.setText("Address");
   
   
   
   
    TextView name=(TextView)viewdialog1.findViewById(R.id.namse);
    TextView name1=(TextView)viewdialog1.findViewById(R.id.namse1);
    TextView name2=(TextView)viewdialog1.findViewById(R.id.namse2);
    TextView name3=(TextView)viewdialog1.findViewById(R.id.namse3);
    TextView name4=(TextView)viewdialog1.findViewById(R.id.namse4);
   
    Button close=(Button)viewdialog1.findViewById(R.id.close);
   
    name.setTypeface(tf);
    name1.setTypeface(tf);
    name2.setTypeface(tf);
    name3.setTypeface(tf);
    name4.setTypeface(tf);
   
    close.setTypeface(tf);
   
    close.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
viewdialog1.dismiss();
}
});
   
   

   
   
    name.setText(knownName);
    name1.setText(address);
    name2.setText(city);
    name3.setText(state);
    name4.setText(postalCode);

    viewdialog1.show();
   
   
   
   
   
                   


} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}




                   
                    }
                });

                // Returning the view containing InfoWindow contents
                return v;

            }
        });

           
         


}

}



class drawpath extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {






             try {
update();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

         return null;
}



private void update()

{

try {
int minu=totallength-1;
for (int i = 0; i < totallength; i++)
{

int ju=0;
ju=i+1;

if(ju==totallength)
{

}
else
{
try {
Double lat=Double.parseDouble(latitude[i]);
  Double lon=Double.parseDouble(longitude[i]);

  Double lat1=Double.parseDouble(latitude[ju]);
  Double lon1=Double.parseDouble(longitude[ju]);



   origin = new LatLng(lat, lon);
dest = new LatLng(lat1, lon1);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}



   
     
  try {
String url = getDirectionsUrl(origin, dest);

  DownloadTask downloadTask = new DownloadTask();

  // Start downloading json data from Google Directions API
  downloadTask.execute(url);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}



protected void onPostExecute(String result) {

}
}

private String getDirectionsUrl(LatLng origin,LatLng dest){
       
        // Origin of route
        String str_origin = "origin="+origin.latitude+","+origin.longitude;
     
        // Destination of route
        String str_dest = "destination="+dest.latitude+","+dest.longitude;     
                 
        // Sensor enabled
        String sensor = "sensor=false";         
             
        // Waypoints
        String waypoints = "";
     
       
            LatLng point  = origin;
         
                waypoints = "waypoints=";
            waypoints += point.latitude + "," + point.longitude + "|";
     
     
                 
        // Building the parameters to the web service
        String parameters = str_origin+"&"+str_dest+"&"+sensor+"&"+waypoints;
                 
        // Output format
        String output = "json";
     
        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
     
     
        return url;
    }

    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
                URL url = new URL(strUrl);

                // Creating an http connection to communicate with url
                urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url
                urlConnection.connect();

                // Reading data from url
                iStream = urlConnection.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                StringBuffer sb  = new StringBuffer();

                String line = "";
                while( ( line = br.readLine())  != null){
                        sb.append(line);
                }
             
                data = sb.toString();

                br.close();

        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
        }finally{
                iStream.close();
                urlConnection.disconnect();
        }
        return data;
     }
 
 
    private class DownloadTask extends AsyncTask<String, Void, String>{         
       
        // Downloading data in non-ui thread
        @Override
        protected String doInBackground(String... url) {
             
            // For storing data from web service
            String data = "";
                 
            try{
                // Fetching the data from web service
                data = downloadUrl(url[0]);
            }catch(Exception e){
                Log.d("Background Task",e.toString());
            }
            return data;     
        }
     
        // Executes in UI thread, after the execution of
        // doInBackground()
        @Override
        protected void onPostExecute(String result) {         
            super.onPostExecute(result);         
         
            try {
ParserTask parserTask = new ParserTask();
       
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
             
        }     
    }
 
 
    /** A class to parse the Google Places in JSON format */
    private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
     
        // Parsing the data in non-ui thread     
        @Override
        protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
         
            JSONObject jObject; 
            List<List<HashMap<String, String>>> routes = null;                   
         
            try{
                jObject = new JSONObject(jsonData[0]);
                DirectionsJSONParser parser = new DirectionsJSONParser();
             
                // Starts parsing data
                routes = parser.parse(jObject); 
            }catch(Exception e){
                e.printStackTrace();
            }
            return routes;
        }
     
        // Executes in UI thread, after the parsing process
        @Override
        protected void onPostExecute(List<List<HashMap<String, String>>> result) {
         
            try {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
       
// Traversing through all the routes
for(int i=0;i<result.size();i++){
    points = new ArrayList<LatLng>();
    lineOptions = new PolylineOptions();
 
    // Fetching i-th route
    List<HashMap<String, String>> path = result.get(i);
 
    // Fetching all the points in i-th route
    for(int j=0;j<path.size();j++){
        HashMap<String,String> point = path.get(j);                 
     
        double lat = Double.parseDouble(point.get("lat"));
        double lng = Double.parseDouble(point.get("lng"));
        LatLng position = new LatLng(lat, lng); 
     
        points.add(position);                     
    }
 
    // Adding all the points in the route to LineOptions
    lineOptions.addAll(points);
    lineOptions.width(6);
    lineOptions.color(Color.BLUE);             
}
       
// Drawing polyline in the Google Map for the i-th route
myMap.addPolyline(lineOptions);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}                         
        }         
    }

 

 

public static Bitmap createDrawableFromView(Context context, View view) {
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

Canvas canvas = new Canvas(bitmap);
view.draw(canvas);

return bitmap;



}


Screenshot:-




DOWNLOAD PERSONTRACK.ZIP



No comments:

Post a Comment

back to top