0

Here i am not using google maps.Is it necessary to use google maps to find out the distance between two points?I am getting two points using gecoder.So i think that is enough.I am not getting the return value from the called method.Pls look at the code below

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.List;
    import java.util.Locale;

    import org.json.JSONArray;

    import org.json.JSONObject;
    import org.json.JSONTokener;
    import android.app.Activity;
    import android.location.Address;
    import android.location.Geocoder;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;

    public class WhereDoYouLive extends Activity {
        /** Called when the activity is first created. */


         double latitude ;
        double longitude ;
         double latitude2 ;
        double longitude2 ;
        String sDistance;
        int iDistance;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);  // Set up GUI

            final EditText addressfield = (EditText) findViewById(R.id.address);  // Reference edit field
            final EditText addressfield2 = (EditText) findViewById(R.id.secaddress);
            final Button launchmapbtn = (Button) findViewById(R.id.launchmap);  // Reference search button
          final TextView lat=(TextView)findViewById(R.id.lat);
          final TextView lon=(TextView)findViewById(R.id.lon);
          final TextView lat2=(TextView)findViewById(R.id.lat2);
          final TextView lon2=(TextView)findViewById(R.id.lon2);
          final TextView result=(TextView)findViewById(R.id.res);
          String lt2;



            launchmapbtn.setOnClickListener(new OnClickListener(){  
                    public void onClick(View v) { 
                        // List<Address> addresses=null;
                         String aa=addressfield.getText().toString();
                         String bb=addressfield2.getText().toString();
                         Geocoder geocoder = new Geocoder(getApplicationContext(),Locale.getDefault()); 


                        try {

    List<Address> addresses;
    addresses = geocoder.getFromLocationName(aa, 1);

    if(addresses.size() > 0) {
         latitude= addresses.get(0).getLatitude();
         longitude= addresses.get(0).getLongitude();
       String lt=Double.toString(latitude);
        String lg=Double.toString(longitude);
        lat.setText(lt);
        lon.setText(lg);
    }

    List<Address> addresses2 ;
    addresses2 = geocoder.getFromLocationName(bb, 1);

    if(addresses2.size() > 0) {
         latitude2= addresses2.get(0).getLatitude();
         longitude2= addresses2.get(0).getLongitude();
        String lt2=Double.toString(latitude2);
        String lg2=Double.toString(longitude2);
       lat2.setText(lt2);
        lon2.setText(lg2);

         }

    int Roaddistance=GetDistance(latitude, longitude, latitude2, longitude2);
    String fd=Integer.toString(Roaddistance);
    result.setText(fd);
                } catch (Exception e){


                        }   



        }
    });
}



 public    int GetDistance(double lat1, double lon1, double lat2, double lon2) {

        Log.d("lat1", Double.toString(lat1));
        Log.d("lon", Double.toString(lon1));
        Log.d("lat1", Double.toString(lat1));
        Log.d("lon", Double.toString(lon1));
        StringBuilder urlString = new StringBuilder();
        urlString.append("http://maps.googleapis.com/maps/api/directions/json?");
        urlString.append("origin=");//from
        urlString.append( Double.toString(lat1));
        urlString.append(",");
        urlString.append( Double.toString(lon1));
        urlString.append("&destination=");//to
        urlString.append( Double.toString(lat2));
        urlString.append(",");
        urlString.append( Double.toString(lon2));
        urlString.append("&mode=walking&sensor=true");
        Log.d("xxx","URL="+urlString.toString());

        // get the JSON And parse it to get the directions data.

        try {
        HttpURLConnection urlConnection= null;
        URL url = null;







            url = new URL(urlString.toString());
            urlConnection=(HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.connect();

            InputStream inStream = urlConnection.getInputStream();
            BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));

            String temp, response = "";
            while((temp = bReader.readLine()) != null){
                //Parse data
                response += temp;
            }
            //Close the reader, stream & connection
            bReader.close();
            inStream.close();
            urlConnection.disconnect();

            //Sortout JSONresponse 
            JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
            JSONArray array = object.getJSONArray("routes");
                //Log.d("JSON","array: "+array.toString());

            //Routes is a combination of objects and arrays
            JSONObject routes = array.getJSONObject(0);
                Log.d("JSON","routes: "+routes.toString());

            String summary = routes.getString("summary");
                Log.d("JSON","summary: "+summary);

            JSONArray legs = routes.getJSONArray("legs");
                Log.d("JSON","legs: "+legs.toString());

            JSONObject steps = legs.getJSONObject(0);
                    //Log.d("JSON","steps: "+steps.toString());

            JSONObject distance = steps.getJSONObject("distance");
                Log.d("JSON","distance: "+distance.toString());

                     sDistance = distance.getString("text");
                     iDistance = distance.getInt("value");

                     Log.d("distance: ",sDistance);
                     Log.d("distance: ",Integer.toString(iDistance));



        } catch (Exception e) {
            // TODO: handle exception
        }


        Log.d("distance: ",sDistance);
        Log.d("distance: ",Integer.toString(iDistance));

                return iDistance ;
    }




}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <TextView 
        android:id="@+id/lat" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" />

      <TextView 
        android:id="@+id/lon" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" />

      <TextView 
        android:id="@+id/lat2" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" />

      <TextView 
        android:id="@+id/lon2" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" />
      <TextView 
        android:id="@+id/res" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" />


<EditText 
android:text="Enter your address" 
android:id="@+id/address" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content">
</EditText>

<EditText 
android:text="Enter your secondaddress" 
android:id="@+id/secaddress" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content">
</EditText>

<Button 
android:text="Search" 
android:id="@+id/launchmap" 
android:layout_width="150px" 
android:layout_height="wrap_content">
</Button>

</LinearLayout>

android manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.book.wheredoyoulive"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="Search Pro" >
        <activity android:name=".WhereDoYouLive"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>


</manifest> 
DJ Burb
  • 2,346
  • 2
  • 29
  • 38
zyonneo
  • 1,319
  • 5
  • 25
  • 63
  • possible duplicate of [Calculating distance between two geographic locations](http://stackoverflow.com/questions/8049612/calculating-distance-between-two-geographic-locations) – tyczj Nov 19 '14 at 18:40
  • Add an example url that doesn't work. – Simas Nov 19 '14 at 18:40
  • Not duplicate it is different.I want to use JSON and find the distance – zyonneo Nov 20 '14 at 08:02

1 Answers1

-1

Use location1.distanceto(location2) to get the value in meters. where location1 and location2 are source and destination respectively. And it is not necessary to use google maps to find this distance. Cheers

therealprashant
  • 701
  • 15
  • 27
  • This just finds straight distance, Google Directions API will follow streets. – Simas Nov 19 '14 at 18:52
  • @user3249477 op did not specify if he wanted a straight line or route distance – tyczj Nov 19 '14 at 18:55
  • It's a comment on the functionality of this method, which you skipped. No need to rage :) – Simas Nov 19 '14 at 19:01
  • 1
    @ user3249477 not raging sorry for that if you felt but I answered according to the question – therealprashant Nov 19 '14 at 19:09
  • i want the distance via road.So when i am giving the locations via textbox.So am getting the URL like this. http://maps.googleapis.com/maps/api/directions/json?origin=8.4790972,76.9657463&destination=8.5580957,76.8807437&mode=walking&sensor=true .In this the distacne 15.5 km is clearly given i want that distance value as return type.I think it is done using JSON. – zyonneo Nov 20 '14 at 07:41