0

I created an app composed of google map and listview of places. The data of places is in the SQLite together with the latitude and longitude. I decided to add a button wherein if the user clicks it, nearby location will appear based on the location of the user in listview and it will replace the previous listview and the markers will appear in the map. I dont have an idea how to display the nearby location once I click a button. In my project, all the list of places already displays in the listview and once the users selects in the list, map will automatically get the latitude of longitude. Please help me.

public class MainActivity extends AppCompatActivity implements LocationListener {

    GoogleMap map;

    List<LocationModel> GetLocation;
    Context context = this;
    DatabaseHelper dbhelper;
    DatabaseHelper db = new DatabaseHelper(this);
    ListView lv;
    View yourListView,yourProfileView;
    Button buttonnearby;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dbhelper = new DatabaseHelper(MainActivity.this);


        buttonnearby = (Button) findViewById(R.id.button);
        buttonnearby.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View convertView) {


            }

        });

        try{
            dbhelper.createDataBase();
        }
        catch(IOException e){
            e.printStackTrace();
        }
        try {
            dbhelper.openDataBase();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        GetLocation = dbhelper.getLocation();
        lv = (ListView) findViewById(R.id.listView);
        lv.setAdapter(new ViewAdapter());

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                LatLng latlngtofocus = new LatLng(Double.parseDouble(GetLocation.get(i).getlatitude()),  Double.parseDouble(GetLocation.get(i).getlongitude()));

                map.animateCamera(CameraUpdateFactory.newLatLngZoom(latlngtofocus, 17.0f));

                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(latlngtofocus);
                //adding marker to the map
                map.addMarker(markerOptions);


                yourListView = findViewById(R.id.layout);
                ViewGroup parent = (ViewGroup) yourListView.getParent();
                parent.removeView(yourListView);
// inflate your profile view (or get the reference to it if it's already inflated)
                yourProfileView = getLayoutInflater().inflate(R.layout.profile_location, parent, false);
// add it to the parent
                parent.addView(yourProfileView);

            }


        });



        //To get MapFragment reference from xml layout
        MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);

        //To get map object
        map = mapFragment.getMap();
        map.getUiSettings().setZoomControlsEnabled(true);

       /* //to show current location in the map
        map.setMyLocationEnabled(true);

        map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {

                Toast.makeText(getApplicationContext(), latLng.toString(), Toast.LENGTH_LONG).show();
            }
        });*/

        //To setup location manager
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        //To request location updates
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, this);

    }


    @Override
    public void onLocationChanged(Location location) {

        //To clear map data
        map.clear();

        //To hold location
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

        //To create marker in map
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("My Location");
        //adding marker to the map
        map.addMarker(markerOptions);

        //opening position with some zoom level in the map
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17.0f));
    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    /****************************************************************************************
     *                                      CUSTOM LIST
     ****************************************************************************************/
    public class ViewAdapter extends BaseAdapter {

        LayoutInflater mInflater;

        public ViewAdapter() {
            mInflater = LayoutInflater.from(context);
        }

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

        @Override
        public Object getItem(int position) {
            return null;
        }

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

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

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_location,null);
            }

            final TextView place = (TextView) convertView.findViewById(R.id.location);
            final TextView latitude = (TextView) convertView.findViewById(R.id.latitude);
            final TextView longitude = (TextView) convertView.findViewById(R.id.longitude);

            location.setText(GetLocation.get(position).getlocation());
            latitude.setText(GetLocation.get(position).getlatitude());
            longitude.setText(GetLocation.get(position).getlongitude());

            return convertView;
        }
    }

    @Override
    public void onBackPressed() {
        if(yourProfileView != null && yourProfileView.getParent() != null) {
            // remove your profile view
            ViewGroup parent = (ViewGroup) yourProfileView.getParent();
            parent.removeView(yourProfileView);

            // a reference to yourListView has to be saved somewhere; just get it

            // add your listview to the parent
            parent.addView(yourListView);
        } else {
            super.onBackPressed();
        }
    }

}

DatabaseHelper

public List<LocationModel> getLocation() {


        List<LocationModel> lList = new ArrayList<LocationModel>();
        {
            String selectQuery =
                    "SELECT id,location,latitude,longitude FROM places ";
            Log.e("places query: ", selectQuery);
            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);

            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    LocationModel lm = new LocationModel();
                    lm.setid(Integer.parseInt(cursor.getString(0)));
                    lm.setlocation(cursor.getString(1));
                    lm.setlatitude(cursor.getString(2));
                    lm.setlongitude(cursor.getString(3));

                    lList.add(lm);
                } while (cursor.moveToNext());
            }
            db.close();
        }
        return lList;
    }
}
APCM
  • 1,704
  • 1
  • 11
  • 24

3 Answers3

2

If you want to get the distance between two lat lng pairs the easiest way is to use the .distanceBetween() function in Location:

float [] distResult = new float[1];
Location.distanceBetween(latA, lonA, latB, lonB, distResult);
float dist = distResult[0];
drdawud
  • 73
  • 8
  • how to use that code in my code?sorry newbie in android especially in google map – APCM Nov 04 '15 at 04:51
  • nice :D this is really simple. – Martin Pfeffer Nov 04 '15 at 05:17
  • Maybe I misunderstood. What exactly do you need help with? This code will help you find the distance between points, the smallest of which will indicate the closest point to the user's location. – drdawud Nov 04 '15 at 18:17
0

After you get your user location, you will need to calculate the distance between your list of location and show it on the map based on a radius limit you might want to show to the user, for example: to show location within 2miles radius of the current user location.

John
  • 49
  • 6
0

Please keep in mind that distances between longs and lats can vary in some circumstances. At the north pole the distance between two longs isn't as much as it is near the equator (see the wikipedia picture down below to get an idea). This specific issue you can solve by this function:

public static double geoCoordToMeter(double latA, double lonA, double latB, double lonB) {
    double earthRadius = 6378.137d; // km
    double dLat = (latB - latA) * Math.PI / 180d;
    double dLon = (lonB - lonA) * Math.PI / 180d;
    double a = Math.sin(dLat / 2d) * Math.sin(dLat / 2d)
               + Math.cos(latA * Math.PI / 180d)
                 * Math.cos(latB * Math.PI / 180d)
                 * Math.sin(dLon / 2d) * Math.sin(dLon / 2);
    double c = 2d * Math.atan2(Math.sqrt(a), Math.sqrt(1d - a));
    double d = earthRadius * c;
    return (d * 1000d);
}

That being said you will focus on the values you receive. Here you can loop through the database and check whats the lowest. To deal with this is not so hard... pseudo coding:

private int mMinValue = 10000; // field (member which stores the lowest..)

private checkMin(int newMin){
           if(mMinValue < newMin) mMinValue = newMin;
    }

If you don't want to deal with geo-data yourself, maybe the Geofence-API will do the mathematical stuff for you. ;) I don't have any experiances with this API, maybe you have to do some research, to know if it's useful or not.

Hope it helps.

wikipedia

Martin Pfeffer
  • 12,471
  • 9
  • 59
  • 68
  • Can u please help me here? http://stackoverflow.com/questions/33492505/how-to-retrieve-a-set-of-locations-within-particular-range-from-users-location?noredirect=1#comment54808178_33492505 – Jas Nov 04 '15 at 03:59
  • if you want to display correct values, you better "convert" them, yes.. otherwise an user in Africa will see other values then a Norwegian (when they stay in real **both** 500m away from their point of interest). – Martin Pfeffer Nov 04 '15 at 05:07
  • i still didnt get it sorry :( i dont know how to apply it in my code @MartinPfeffer – APCM Nov 04 '15 at 05:37