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!