Thursday, February 27, 2014

Easiest way to get current location on an android

The newest update of the NY Coffee Map app has a feature to launch navigation to the nearest coffee shop on the map. Android makes location-finding easy. Every device can find its coordinates through GPS  and NETWORK (includes cell tower triangulation and WiFi) It has it's own class "Criteria" to determine which of these is best, taking into account battery, accuracy, whats on, etc.
Here's code (nestled in onCreate) to find the Location we've cleverly named 'devicelocation'

Criteria criteria = new Criteria(); provider = locationManager.getBestProvider(criteria, true); 
Location devicelocation = locationManager.getLastKnownLocation(provider);

n.b. The true in the .getBestProvider tells the method to only select a provider that is currrently enabled.
Once you have that location, getting the latitude an longitude is as easy as requesting it! We save them as doubles called 'currentlat' and 'currentlong'


currentlat = location.getLatitude();
currentlong = location.getLongitude();

And, bingo, you have your latitude and longitude coordinates saved. Note that since we put the Location code in onCreate, we only get a new set of coordinates when the Activity is launched. Adding this method to your code, outside of onCreate obviously, will give you more updates:

@Overrideprotected void onResume() {
  super.onResume();

  if (provider != null){    
    locationManager.requestLocationUpdates(provider, 400, 1, this);
  }

}

@Override 
public void onLocationChanged(Location location) { 
  currentlat = location.getLatitude(); 
  currentlong = location.getLongitude(); 
}

In the next post, I will show how to launch navigation to get to these coordinates!

3 comments:

  1. How do you fix the Cannot resolve symbol 'provider' and 'locationManager' issue? also, what Permission to you set in manifest?

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Jed: You have to have " " in your manifest and "import android.location.LocationManager;" in your file. See my gist: https://gist.github.com/ChrisGuzman/cc39805a395f4d44e5fa

      I don't know about the 'provider' issue. But I bet you have to import a file.

      Delete