2

I have in my hand the latitude and longitude values of several places in my server. These latitude and longitude values are sent from the server and received at the android mobile successfully. Now I need to get the current location of my android phone and calculate the nearest place to my current location and mark it on the google map. I know how to mark a place on the google map, but I don't know how to calculate distances from my current location to other locations using latitude and longitude and find the shortest distance places from my location. Also I don't know how to get my current location from an android device using coding. I have heard that the location can be found out by two ways such as 1) using last known location and 2) by using onlocation changed. The current location using last known location method does not suite for my application. So I need to get my current latitude and longitude using onlocation changed. If its not available, then get the location coordinates from latitude and longitude.

This is the code in which I have opened google maps in my app and marked a place using a latitude and longitude.

public class Map extends Activity {

private GoogleMap googleMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    try {
        // Loading map
        initilizeMap();

    } catch (Exception e) {
        e.printStackTrace();
    }
    double latitude =9.887262 ;
    double longitude = 76.731675;

    // create marker
    MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps ");

    // adding marker
    googleMap.addMarker(marker);
    CameraPosition cameraPosition = new CameraPosition.Builder().target(
            new LatLng(latitude, longitude)).zoom(12).build();

googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));


}

private void initilizeMap() {
    if (googleMap == null) {
        googleMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}

@Override
protected void onResume() {
    super.onResume();
    initilizeMap();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.map, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

This is its layout file..

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

<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.MapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>


</RelativeLayout>
njnjnj
  • 978
  • 4
  • 23
  • 58

2 Answers2

1

Use the following method to calculate distances

    private double distance(double lat1, double lon1, double lat2, double lon2) {
      double theta = lon1 - lon2;
      double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
      dist = Math.acos(dist);
      dist = rad2deg(dist);
      dist = dist * 60 * 1.1515;
       return (dist);
    }

   private double deg2rad(double deg) {
      return (deg * Math.PI / 180.0);
    }
   private double rad2deg(double rad) {
      return (rad * 180.0 / Math.PI);
    }
Supriya
  • 1,078
  • 1
  • 8
  • 16
  • How to get my current location using onlocation changed.? – njnjnj Sep 20 '14 at 04:59
  • in onLocation changed method you can get `location.getLatitude()` and `location.getLongitude()`. – Piyush Sep 20 '14 at 05:12
  • get current location using locationClient. Try something like this: [http://stackoverflow.com/questions/16731717/using-locationclient-to-get-location-updates] – Supriya Sep 20 '14 at 06:19
1

For the purpose of calculating distances from one point to another, there are various algorithms available but what these algorithms does is, they just calculate the straight line distance between the two points. If you want to actually get the practical path length between the points you will be better off using the Google Directions API.

You can make use of a HttpURLConnection to query Google's server to obtain a JSON which contains all the details about the distance as well as the route between the two points. You can parse the JSON using:

public class DistanceCalculator {

private String dist;

public String getDistance(String data) {
    try {
        JSONObject json = new JSONObject(data);
        System.out.println("\n\nParsed JSON: " + json);
        JSONArray routes = json.getJSONArray("routes");
        System.out.println("\n\n\tRoutes Array: " + routes);
        for (int i = 0; i < routes.length(); i++) {
            JSONObject route = routes.getJSONObject(i);
            System.out.println("\n\n\tRoute " + i + ": " + route);
            JSONArray legs = route.getJSONArray("legs");
            System.out.println("\n\n\t\tLegs Array:  " + legs);
            for (int k = 0; k < legs.length(); k++) {
                JSONObject leg = legs.getJSONObject(k);
                System.out.println("\n\n\t\t\tLeg " + k + ": " + leg);
                JSONObject distance = leg.getJSONObject("distance");
                dist = distance.getString("text");
                System.out.println("\n\n\t\t\tDistance: " + dist);
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return dist;
}

}

After you obtain the JSON object you can use the data from it to plot the route on your map. There are algorithms available on the web which you can use to achieve this. Here is a good example of how to do that : http://javapapers.com/android/draw-path-on-google-maps-android-api/

shyam
  • 1,348
  • 4
  • 19
  • 37