0

Possible Duplicate:
What is the simplest and most robust way to get the user’s current location in Android?

I have the following code that opens up Google Maps on the phone and passes the longitude + latitude of the destination and start location to it. I was wondering though if there was a way so that instead of having to manually enter a starting location into the code, if we could instead somehow get the code to automatically find out where the user is?

add.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        Intent intent = new Intent (android.content.Intent.ACTION_VIEW,
            Uri.parse("http://maps.google.com/maps?saddr=" + 51.5171 +
                      "," + 0.1062 + "&daddr=" + 52.6342 + "," + 1.1385));

        intent.setComponent(
            new ComponentName ("com.google.android.apps.maps",
                               "com.google.android.maps.MapsActivity"));

        startActivity(intent);
    }
});
Community
  • 1
  • 1
JimmyK
  • 4,801
  • 8
  • 35
  • 47

3 Answers3

2

You can use this method:

public LatLng getLocation(Context ctx) 
{
    LocationManager lm = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = lm.getProviders(true);

    /*
     * Loop over the array backwards, and if you get an accurate location,
     * then break out the loop
     */
    Location l = null;

    for (int i = providers.size() - 1; i >= 0; i--) 
    {
        l = lm.getLastKnownLocation(providers.get(i));
        if (l != null)
            break;
    }
    return new LatLng(l.getLatitude(),l.getLongitude());
}
Tamás Cseh
  • 3,050
  • 1
  • 20
  • 30
0

Refer to this question: What is the simplest and most robust way to get the user's current location on Android?

Basically once you acquire your Location, you can use getLatitude(), getLongitude() and drop those into your url.

I would recommend something more robust than getLastKnownLocation as it relies on the last known location, which may not have been updated in hours or possibly even days. If you're on vacation for instance, this could be on the wrong side of the planet.

Also view http://developer.android.com/guide/topics/location/strategies.html for more details.

Community
  • 1
  • 1
Uxonith
  • 1,602
  • 1
  • 13
  • 16
-1

Step by step guide for your question:

http://www.androidcompetencycenter.com/?s=GPS

Hope this helps

Ramesh Sangili
  • 1,633
  • 3
  • 17
  • 31