How To Find Nearby Places

XML Files:-

trackmain.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/maptransparent"
        android:gravity="center"
        android:orientation="vertical" >

        <Button
            android:id="@+id/button1"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:background="@drawable/trafficneww" />
    </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>

JAVA Files:-

Trackmainactivity.java

package com.parthivlocationnearplaces.in;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
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.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.media.MediaPlayer;
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.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.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;

@SuppressLint("NewApi") @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public class Trackmainactivity 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;

 Typeface tf;
 String fontPath = "fonts/Smoolthan Bold.otf";
 String datetoserver;
 private final long startTime = 10 * 1000;
 private final long interval = 1 * 1000;
 private double curLatitude = 0, curLongtitude = 0;
 ProgressBar load;
 Mylocation gps;
 TextView placee,descrip,distancec;
 Button okk;
 MediaPlayer mp;
 String address,city,state,country,postalCode,knownName;
 double lat,lon;


 @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.trackmain);
  tf= Typeface.createFromAsset(getAssets(),
fontPath);
  gps = new Mylocation(Trackmainactivity.this);

  // Check if GPS enabled
  if(gps.canGetLocation()) {

      curLatitude = gps.getLatitude();
      curLongtitude = gps.getLongitude();
      //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + curLatitude + "\nLong: " + curLongtitude, Toast.LENGTH_LONG).show();
  } else {
   
      gps.showSettingsAlert();
  }


  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 PROBLEM?");
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);

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



 }

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 ="PASTE YOUR URL";
} 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();
}


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

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

                                        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                                        System.out.println("time dif "+i+"------>"+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++)
{

  lat=Double.parseDouble(latitude[i]);
  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(Trackmainactivity.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(Trackmainactivity.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(Trackmainactivity.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(Trackmainactivity.this, marker))));
  builder.include(Leicester_Square);
  }

  //current location marker
    myMap.addMarker(new MarkerOptions()
                .position(new LatLng(curLatitude, curLongtitude))
                .draggable(true)
                .snippet("Hello")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));



    float distance = distFrom(curLatitude, curLongtitude, lat,
lon);
double dist = distFromLatLong(curLatitude, curLongtitude,
lat, lon);
Log.e("Distance in meter ", "" + lat + " , " + lon + " is "
+ "" + distance);
Log.e("Distance in KM ", "" + lat + " , " + lon + " is "
+ "" + dist);
//String disstr = String.valueOf(dist);
String disstr = String.valueOf(Math.round(dist));




if(dist<10){

  final Dialog dg1 = new Dialog(Trackmainactivity.this);
              dg1.requestWindowFeature(Window.FEATURE_NO_TITLE);
              dg1.setContentView(R.layout.notificationpopup);
              dg1.setCancelable(true);
        dg1.setCanceledOnTouchOutside(true);
      placee=(TextView)dg1.findViewById(R.id.placeid);
      descrip=(TextView)dg1.findViewById(R.id.desc);
      distancec=(TextView)dg1.findViewById(R.id.distance);
                                    placee.setText(""+busno[i]);
      placee.setTypeface(tf);
      distancec.setText(""+busno[i]+" AWAY FROM "+disstr+" KM");
      distancec.setTypeface(tf);
     
      double notifilat=Double.parseDouble(latitude[i]);
      double notifilong=Double.parseDouble(longitude[i]);
     
     
try {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(Trackmainactivity.this, Locale.getDefault());

addresses = geocoder.getFromLocation(notifilat, notifilong, 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();

}
descrip.setText(""+address);
                                      descrip.setTypeface(tf);
 
                                  mp= MediaPlayer.create(Trackmainactivity.this, R.raw.tone);
                            mp.start();
 
                                  okk=(Button)dg1.findViewById(R.id.closebtn);
                                  okk.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
dg1.dismiss();
}
                                         });
                                   dg1.show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 
  }

  }


}
} 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);
            yes.setText("Click to see full Address?");

                    myMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {       
                    public void onInfoWindowClick(Marker marker)
                    {
                   
                    //click get lat and long
                    Double latitudeff = marker.getPosition().latitude;
                    Double longitudeff = marker.getPosition().longitude;
                   
                    try {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(Trackmainactivity.this, Locale.getDefault());

addresses = geocoder.getFromLocation(latitudeff, longitudeff, 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(Trackmainactivity.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 name1=(TextView)viewdialog1.findViewById(R.id.namse1);
   
   
    Button close=(Button)viewdialog1.findViewById(R.id.close);
   
   
    name1.setTypeface(tf);
   
    close.setTypeface(tf);
   
    close.setOnClickListener(new OnClickListener() {

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

    viewdialog1.show();
   

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

                    }
                });

                // Returning the view containing InfoWindow contents
                return v;

            }
        });

         
       


}

}



public static float distFrom(double lat1, double lng1, double lat2,
double lng2) {
double earthRadius = 6371000; // meters
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)
* Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
float dist = (float) (earthRadius * c);

return dist;
}
private static double distFromLatLong(double latA, double lngA,
double latB, double lngB) {
double distance;
Location locationA = new Location("point A");
locationA.setLatitude(latA);
locationA.setLongitude(lngA);
Location locationB = new Location("point B");
locationB.setLatitude(latB);
locationB.setLongitude(lngB);
// distance = locationA.distanceTo(locationB); //in meters
distance = locationA.distanceTo(locationB) / 1000; // in km

return distance;
}


 
 
   
    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;
    }
   
    @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);
      }
    }
 
   

}

Mylocation.java

package com.parthivlocationnearplaces.in;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class Mylocation extends Service implements LocationListener {

    private final Context mContext;

    // Flag for GPS status
    boolean isGPSEnabled = false;

    // Flag for network status
    boolean isNetworkEnabled = false;

    // Flag for GPS status
    boolean canGetLocation = false;

    Location location; // Location
    double latitude; // Latitude
    double longitude; // Longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public Mylocation(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // Getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // Getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // No network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // If GPS enabled, get latitude/longitude using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }


    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app.
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(Mylocation.this);
        }
    }


    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }


    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/Wi-Fi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }


    /**
     * Function to show settings alert dialog.
     * On pressing the Settings button it will launch Settings Options.
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing the Settings button.
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // On pressing the cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }


    @Override
    public void onLocationChanged(Location location) {
    }


    @Override
    public void onProviderDisabled(String provider) {
    }


    @Override
    public void onProviderEnabled(String provider) {
    }


    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }



}

DirectionsJSONParser.java

package com.parthivlocationnearplaces.in;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.maps.model.LatLng;

public class DirectionsJSONParser
{

/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
public List<List<HashMap<String, String>>> parse(JSONObject jObject)
{
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
JSONObject jDistance = null;
JSONObject jDuration = null;

try
{
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for (int i = 0; i < jRoutes.length(); i++)
{
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List<HashMap<String, String>> path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for (int j = 0; j < jLegs.length(); j++)
{
/** Getting distance from the json data */
jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
HashMap<String, String> hmDistance = new HashMap<String, String>();
hmDistance.put("distance", jDistance.getString("text"));

/** Getting duration from the json data */
jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
HashMap<String, String> hmDuration = new HashMap<String, String>();
hmDuration.put("duration", jDuration.getString("text"));

/** Adding distance object to the path */
path.add(hmDistance);

/** Adding duration object to the path */
path.add(hmDuration);

jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

/** Traversing all steps */
for (int k = 0; k < jSteps.length(); k++)
{
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = this.decodePoly(polyline);

/** Traversing all points */
for (int l = 0; l < list.size(); l++)
{
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString((list.get(l)).latitude));
hm.put("lng", Double.toString((list.get(l)).longitude));
path.add(hm);
}
}
}
routes.add(path);
}

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

return routes;
}

/**
* Method to decode polyline points
* Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
private List<LatLng> decodePoly(String encoded)
{

List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;

while (index < len)
{
int b, shift = 0, result = 0;
do
{
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;

shift = 0;
result = 0;
do
{
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;

LatLng p = new LatLng(((lat / 1E5)), ((lng / 1E5)));
poly.add(p);
}

return poly;
}

}

Screenshots:-










No comments:

Post a Comment

back to top