根据不同类型用户的位置获取距离

时间:2016-08-19 10:45:47

标签: android json google-maps

用于解析列表视图的网址: -

http://c0897edf.ngrok.io/api/v1/restaurants?per_page=5&km=1&location=true&lat=19.0558306414&long=72.8339840099

in the above url, parameters are
 1) restaurants?per_page=5
 2) km=1
 3) location=true
 4) lat=19.0558306414
 5) long=72.8339840099

Note : Latitude & longitude will be set on the basis of user location . So first of all i have to get user's location. 

I have to set latitude & longitude on the basis of user location then pass as a parameter in the url then the list will be appear on this basis.

I am using this code for getting user location :

AndroidGPSTracking.java

   public class AndroidGPSTrackingActivity extends Activity {

            Button btnShowLocation;

            // GPSTracker class
            GPSTracker gps;

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

                btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

                // show location button click event
                btnShowLocation.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {        
                        // create class object
                        gps = new GPSTracker(AndroidGPSTrackingActivity.this);

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

                            double latitude = gps.getLatitude();
                            double longitude = gps.getLongitude();

                            // \n is for new line
                            Log.i("Latitutde", String.valueOf(latitude));
                            Log.i("Longitude",String.valueOf(longitude));

                            Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();    
                        }else{
                            // can't get location
                            // GPS or Network is not enabled
                            // Ask user to enable GPS/network in settings
                            gps.showSettingsAlert();
                        }

                    }
                });
            }

    }

GPSTRACKER.java

public class GPSTracker 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 GPSTracker(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 lat/long 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(GPSTracker.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/wifi enabled
                     * @return boolean
                     * */
                    public boolean canGetLocation() {
                        return this.canGetLocation;
                    }

                    /**
                     * Function to show settings alert dialog
                     * On pressing Settings button will lauch 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 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 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;
                    }

                }

在单独的项目中,我正在使用列表视图,我正在使用: 在这里我正在通过排球库击中网址并解析数据。

ListVIew.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 = "http://c0897edf.ngrok.io/api/v1/restaurants?per_page=15&km=1&location=false&lat=19.0558306414&long=72.8339840099";
                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.setDistance( obj.getString("distance"));
                                            //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;
                    }
                }
            }

CustomListAdapter.java

public class CustomListAdapter extends BaseAdapter {
        private Activity activity;
        private LayoutInflater inflater;
        private List<Movie> movieItems;
        ImageLoader imageLoader = AppController.getInstance().getImageLoader();

        public CustomListAdapter(Activity activity, List<Movie> movieItems) {
            this.activity = activity;
            this.movieItems = movieItems;
        }

        @Override
        public int getCount() {
            return movieItems.size();
        }

        @Override
        public Object getItem(int location) {
            return movieItems.get(location);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (inflater == null)
                inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (convertView == null)
                convertView = inflater.inflate(R.layout.list_row, null);

            if (imageLoader == null)
                imageLoader = AppController.getInstance().getImageLoader();


            NetworkImageView _ImageView = (NetworkImageView) convertView.findViewById(R.id.thumbnail);
             _ImageView.setDefaultImageResId(R.drawable.bc);

            TextView name = (TextView) convertView.findViewById(R.id.name);
            TextView average_ratings = (TextView) convertView.findViewById(R.id.average_ratings);
            TextView address=(TextView) convertView.findViewById(R.id.area);
            TextView cuisine =(TextView) convertView.findViewById(R.id.cuisine);
            TextView cost =(TextView)  convertView.findViewById(R.id.cost);
            TextView distance=(TextView) convertView.findViewById(R.id.Distance);
            //TextView latitude =(TextView) convertView.findViewById(R.id.latitude);
            //TextView longitude=(TextView) convertView.findViewById(R.id.longitude );


            // getting movie data for the row
            Movie m = movieItems.get(position);


            _ImageView.setImageUrl(m.getThumbnailUrl(), imageLoader);
                    // title
            name.setText(m.getName());

            // rating
            average_ratings.setText("Rating: " + String.valueOf(m.getAverage_ratings()));
            address.setText("Area: " + String.valueOf(m.getAddress()));
            //latitude.setText("latitude "+String.valueOf(m.getlatitude() ));
            //longitude.setText("longitude "+String.valueOf(m.getlongitude() ));
            cuisine.setText("Cusine: " + String.valueOf(m.getCuisine()));
            cost.setText("Cost for Two: " + "\t"+"₹"+ String.valueOf(m.getCost()));
            distance.setText("Distance in Km. "+String.valueOf( m.getDistance()));

            return convertView;
        }

        }

Movie.java

public class Movie {
        private String name, thumbnailUrl;

        private String average_ratings;
        private String area;
        private String cuisine;
        private String address;
        private String cost;
        private String longitude;
        private String latitude;
        private Object distance ;


        public Movie() {
        }

        public Movie(String name, String thumbnailUrl, String average_ratings, String area, String cuisine, String address,String cost,String latitude,String longitude,Double distance
        ) {
            this.name = name;
            this.thumbnailUrl = thumbnailUrl;
            //this.year = year;
            this.average_ratings = average_ratings;
            this.area=area;
            this.cuisine=cuisine;
            this.cost=cost;
            this.latitude=latitude;
            this.longitude=longitude;
            this.distance=distance;



    this.address=address;

        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getThumbnailUrl() {
            return thumbnailUrl;
        }

        public void setThumbnailUrl(String thumbnailUrl) {
            this.thumbnailUrl = thumbnailUrl;
        }


        public String getAverage_ratings() {
            return average_ratings;
        }

        public void setAverage_ratings(String average_ratings) {
            this.average_ratings = average_ratings;
        }
        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public String getCuisine() {
            return cuisine;
        }

        public void setCuisine(String cuisine) {
            this.cuisine = cuisine;
        }

            public String getCost() {
                return cost;
            }

            public void setCost(String cost) {
                this.cost = cost;

        }

        public String getlatitude() {
            return latitude;
        }
        public void setlatitude(String latitude ){this.latitude=latitude;}

        public String getlongitude() {
            return longitude;
        }
        public void setlongitude (String longitude ){this.longitude=longitude;}

        public Double getDistance() {
            return (Double) distance;
        }
        public void setDistance(String distance){this.distance=distance;}


    }

我在点击url的基础上得到了这个列表视图 http://c0897edf.ngrok.io/api/v1/restaurants?per_page=5&km=1&location=false&lat=19.0558306414&long=72.8339840099

如何设置用户格度&amp;经度在此网址中动态显示。所以结果会根据那个来获取。 enter image description here

1 个答案:

答案 0 :(得分:0)

请根据您的要求使用我的代码

Location loc1 = new Location("");
loc1.setLatitude(lat1);
loc1.setLongitude(lon1);

Location loc2 = new Location("");
loc2.setLatitude(lat2);
loc2.setLongitude(lon2);

float distanceInMeters = loc1.distanceTo(loc2);

参考:http://developer.android.com/reference/android/location/Location.html#distanceTo(android.location.Location)