5

I have latitude & longitude which are coming from a URL (JSON). I have to calculate the distance from the users location (needs to be determined first) to a particular latitude & longitude basis (which is coming from a URL) and show the distance between those.

The JSON data can be seen on the attached image:

enter image description here

URL for fetching JSON data for (latitude & longitude of restaurant): https://comida-95724.herokuapp.com/api/v1/restaurants/get_featured_restaurants

ListActiivty.java

 public class ListViewActivity extends Activity {
    // Log tag
    private static final String TAG = ListViewActivity.class.getSimpleName();
    // change here url of server api
    private static final String url = "https://comida-95724.herokuapp.com/api/v1/restaurants/get_featured_restaurants";

    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;

    private CustomListAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listview);
        listView = (ListView) findViewById(R.id.list);
        adapter = new CustomListAdapter(this, movieList);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Movie movie = movieList.get(position);
                Intent intent = new Intent(ListViewActivity.this, SecondActivity.class);
                intent.putExtra("name", movie.getName());
                intent.putExtra("average_ratings", movie.getAverage_ratings());
                intent.putExtra("full_address", movie.getAddress());
                intent.putExtra("image_url", movie.getThumbnailUrl());
                intent.putExtra("cuisine",movie.getCuisine());
                intent.putExtra("cost",movie.getCost());
                startActivity(intent);

            }
        });
        listView.setAdapter(adapter);
         pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Please Keep patience.Its loading...");

        pDialog.show();

        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();
                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject obj = response.getJSONObject(i);
                                Movie movie = new Movie();
                                //movie.setTitle(obj.getString("title"));
                                movie.setName(obj.getString("name"));
                                //movie.setThumbnailUrl(obj.getString("image"));
                                movie.setThumbnailUrl(obj.getString("org_image_url"));
                                movie.setAverage_ratings(obj.getString("average_ratings"));
                                movie.setCuisine(obj.getString("cuisine"));
                                movie.setAddress(obj.getJSONObject("address").getString("area"));
                                movie.setlatitude(obj.getJSONObject("address").getString("latitude"));
                                movie.setlongitude(obj.getJSONObject("address").getString("longitude"));
                                movieList.add(movie);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();

            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

}

list_row.xml

 <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/ly_root"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="12dp"
        android:background="#FEFEFE"
        app:cardCornerRadius="8dp">
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <com.android.volley.toolbox.NetworkImageView
                android:id="@+id/thumbnail"
                android:layout_width="120dp"
                android:layout_height="100dp"
                android:layout_marginRight="8dp"
                android:scaleType="centerCrop" />

            <!-- Restaurant name  -->
            <TextView
                android:id="@+id/name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"

                android:layout_toRightOf="@+id/thumbnail"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/area"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/name"
                android:layout_toRightOf="@+id/thumbnail"
                android:textColor="#D2691E"/>

            <!-- Rating -->
            <TextView
                android:id="@+id/average_ratings"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/area"
                android:layout_toRightOf="@+id/thumbnail"
                android:textColor="#D2691E" />

            <TextView
                android:id="@+id/cuisine"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/average_ratings"
                android:layout_toRightOf="@+id/thumbnail"
                android:textColor="#D2691E" />
            <TextView
                android:id="@+id/cost"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/cuisine"
                android:layout_toRightOf="@+id/thumbnail"
                android:textColor="#D2691E" />
    <TextView
            android:id="@+id/latitude"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/cost"
            android:layout_toRightOf="@+id/thumbnail"
            android:textColor="#D2691E" />
        <TextView
            android:id="@+id/longitude"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/latitude"
            android:layout_toRightOf="@+id/thumbnail"
            android:textColor="#D2691E" />
            <TextView
                android:id="@+id/Distance"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/cost"
                android:layout_toRightOf="@+id/thumbnail"
                android:textColor="#D2691E" />
        </RelativeLayout>

    </android.support.v7.widget.CardView>

I am getting the results now like below image. In this i have to show the distance between the user and the particular restaurant:

Example: Distance of user from Yuuka -The St. Regis Mumbai =1.9 km away

How can I show this?

Could anyone please help me?

enter image description here

Ulf Gjerdingen
  • 1,414
  • 3
  • 16
  • 20
user6313669
  • 365
  • 2
  • 7
  • 22
  • It's already answered. Check this [answer](http://stackoverflow.com/a/27943/1281775) by @Chuck. – Seishin Aug 17 '16 at 08:21
  • My question is that how to calculate distance if latitude & longitude is coming via json (URL) ? – user6313669 Aug 17 '16 at 09:14
  • Did you check the answer? It's a function that calculates a distance between two lat&long positions. You have to find out the current position of the user with the device and the point returned from the server. Then calculate the distance with that function. – Seishin Aug 17 '16 at 09:16
  • Yes I have checked but where in my code i have to edit to get the result? Could you please tell me to get desired result ? – user6313669 Aug 17 '16 at 09:23
  • First, when the user opens the app or the specific activity -> find out his location. Second, when you receive the server's response with locations in it, call the mentioned function to calculate the distance between the user and the object. Then present that value to the user. – Seishin Aug 17 '16 at 09:25
  • is there need to store user's location on the server then i would be able to calculate ? – user6313669 Aug 17 '16 at 09:29
  • User's location is different at any time so it will be pointless to store it in the server's database. Another way around is to send the user location in the API call and make the calculations on the server and then return the distance in the response. – Seishin Aug 17 '16 at 09:31
  • Ok it means that first i have to get user location (Latitude,Longitude ) But how to calculate distance because restaurant's location(latitude,longitude) coming from json url. – user6313669 Aug 17 '16 at 09:33

1 Answers1

2

If you know your current location, you can calculate distance between two Location objects in Android as follow:

Location myLocation = new Location("my loc");

myLocation.setLatitude(myLat);
myLocation.setLongitude(myLng);

Location locFromJson = new Location("loc from json");

locFromJson.setLatitude(latFromJson);
locFromJson.setLongitude(lngFromJson);

float distance = myLocation.distanceTo(locFromJson);

Here, distance is in meters. Therefore, distance/1000 will be in kilometers.

Ugurcan Yildirim
  • 5,973
  • 3
  • 42
  • 73