29028

Print Longitude and Latitude in textbox Android

Question:

I have looked about and cannot find any direct threads regarding what I am looking for. I am trying to create an Android application which dials out an emergency number at the push of a button (which I have got working) but cannot get the location (displayed in Longitude and Latitude) to display, I have tried doing it with Toast and EditText boxes. I am new to Android development so wanted to start with something easy, but the LongLat part is being troublesome. Any help would be greatly appreciated.

Below is the code I have been tampering with in order to try and get it to grab the Long and Lat, then in another file I have been trying to use a click listener to assign it to a button so when the button is pressed (in main.xml) it will display the Long and Lat either in a textfield or in toast.

import android.app.Activity; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; import android.widget.TextView; import android.content.Context; import android.location.LocationManager; import android.location.Criteria; public class EmergencyLocation extends Activity implements LocationListener { private TextView latituteField; private TextView longitudeField; private LocationManager locationManager; private String provider; /** Called when the activity is first created. **/ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); latituteField = (TextView) findViewById(R.id.TextView); longitudeField = (TextView) findViewById(R.id.long_lat); // Get the location manager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // Define the criteria how to select the location provider -> use // default Criteria criteria = new Criteria(); provider = locationManager.getBestProvider(criteria, false); Location location = locationManager.getLastKnownLocation(provider); // Initialise the location fields if (location != null) { System.out.println("Provider " + provider + " has been selected."); int lat = (int) (location.getLatitude()); int lng = (int) (location.getLongitude()); latituteField.setText(String.valueOf(lat)); longitudeField.setText(String.valueOf(lng)); } else { latituteField.setText("Provider not available"); longitudeField.setText("Provider not available"); } } private void TextView() { // TODO Auto-generated method stub } @Override public void onLocationChanged(Location arg0) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String arg0) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String arg0) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) { // TODO Auto-generated method stub }}

Answer1:

First, you need to set up a LocationManager:

LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); // set preferred provider based on the best accuracy possible Criteria fineAccuracyCriteria = new Criteria(); fineAccuracyCriteria.setAccuracy(Criteria.ACCURACY_FINE); String preferredProvider = manager.getBestProvider(fineAccuracyCriteria, true);

Now, you have to create a LocationListener. In this case, it calls the method updateLocation():

LocationListener listener = new LocationListener() { public void onLocationChanged(Location location) { // called when a new location is found by the network location provider. updateLocation(location); } public void onStatusChanged(String provider, int status, Bundle extras) {} public void onProviderEnabled(String provider) {} public void onProviderDisabled(String provider) {} };

<strong>EDIT:</strong>

Then, you have to register the listener with your LocationManager (and try to get the cached location):

manager.requestLocationUpdates(preferredProvider, 0, 0, listener); // get a fast fix - cached version updateLocation(manager.getLastKnownLocation());

And finally, the updateLocation() method:

private void updateLocation(Location location) { if (location == null) return; // save location details latitude = (float) location.getLatitude(); longitude = (float) location.getLongitude(); }

<strong>EDIT2:</strong>

OK, just saw your code. In order to make it work, just move around a few bits:

/** Called when the activity is first created. **/ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); latituteField = (TextView) findViewById(R.id.TextView); longitudeField = (TextView) findViewById(R.id.long_lat); // Get the location manager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // Define the criteria how to select the location provider -> use // default Criteria criteria = new Criteria(); provider = locationManager.getBestProvider(criteria, false); locationManager.requestLocationUpdates(provider, 0, 0, this); Location location = locationManager.getLastKnownLocation(provider); onLocationChanged(location); } @Override protected void onDestroy() { super.onDestroy(); locationManager.removeUpdates(this); } @Override public void onLocationChanged(Location location) { if (location != null) { System.out.println("Provider " + provider + " has been selected."); int lat = (int) (location.getLatitude()); int lng = (int) (location.getLongitude()); latituteField.setText(String.valueOf(lat)); longitudeField.setText(String.valueOf(lng)); } else { latituteField.setText("Provider not available"); longitudeField.setText("Provider not available"); } }

Hope it helps!

Answer2:

Quite easy. I use the <em>locationListener</em> as an attribute inside a <em>Location</em> class. Here's how I do it:

package com.rifsoft.android.helper.location; import com.rifsoft.android.helper.IListener; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; public class Location implements IListener { public final static int IDX_LATITIDE = 0; public final static int IDX_LONGITUDE = 1; private double[] lastLocation = {0.0, 0.0}; private LocationManager locationManager = null; private ILocation activity = null; private LocationListener locationListener = new LocationListener() { public void onLocationChanged(android.location.Location location) { // TODO: http://developer.android.com/guide/topics/location/obtaining-user-location.html#BestEstimate lastLocation[IDX_LATITIDE] = location.getLatitude(); lastLocation[IDX_LONGITUDE] = location.getLongitude(); activity.onLocationChange(); } public void onStatusChanged(String provider, int status, Bundle extras) {} public void onProviderEnabled(String provider) {} public void onProviderDisabled(String provider) {} }; /** * Constructor, needs LocationManager * @param activity Activity that will receive the notification when location has changed * @param locationManager LocationManager */ public Location(final ILocation act, LocationManager lm) throws LocationException { if (lm == null) { throw new LocationException(LocationException.ERR_NULL_LOCATION_MANAGER); } if (act == null) { throw new LocationException(LocationException.ERR_NULL_ILOCATION); } locationManager = lm; activity = act; registerListener(); android.location.Location lastCachedLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (lastCachedLocation != null) { lastLocation[IDX_LATITIDE] = lastCachedLocation.getLatitude(); lastLocation[IDX_LONGITUDE] = lastCachedLocation.getLatitude(); } } /** * Retuns last known most accurate location as latitude, longitude * @return Latitude, Longitude */ public double[] getLastLocation() { return lastLocation; } @Override public void registerListener() { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); } @Override public void unRegisterListener() { locationManager.removeUpdates(locationListener); } }

Then the activity.onLocationChange() goes like

public void onLocationChange() { locationUpdated = true; double[] coordinates = location.getLastLocation(); EditText lon = (EditText) activity.findViewById(R.id.longitude_value); lon.setText(String.valueOf(coordinates[Location.IDX_LONGITUDE])); EditText lat = (EditText) activity.findViewById(R.id.latitude_value); lat.setText(String.valueOf(coordinates[Location.IDX_LATITIDE])); }

Recommend

  • Can't use storyboard custom instantiated window controller
  • Is this the right way for a block inside a struct to access a member variable in the same struct?
  • Google Places Autocomplete (included with Places Details) SKU is not getting triggered while using s
  • Call a method of type parameter
  • Java Regex Finding digits in a String
  • Connect SQL Server on button click VB.net
  • VB.Net Exception has been thrown by the target of an invocation
  • How to find the corresponding key value from the string inserted into a QMap?
  • In CloudFlare, present cached page only if cookie is not set
  • Caching of Google Cloud Endpoints?
  • cq5 accessing osgi servlet through Url
  • InternetExplorer.Application with -nomerge switch?
  • Xcode. Image resources added to a test target are not copied into the tests bundle
  • Post-receive hook to pull from bare repo
  • How do you maintain page number after redirect in CakePHP?
  • File structure for PHP-based website
  • How to set and check a session after login?
  • Print a Form at higher dpi than screen resolution
  • Qt fresh Gui application crashes on startup, faulting at QtCore4.dll
  • Embed HTML tag in Flask WTForms field
  • Bash script to bring up and down an interface on loop
  • Using VCL Styles gives a exception / crash in TOpenDialog
  • Using WCF service via async interface from worker thread, how do I ensure that events are sent from
  • Longest `subsequence` of balanced parentheses
  • Highcharts Drawing a line with chart.renderer.path
  • Python C binding error
  • FirebaseAnimatedList change content in real time
  • How to implement JQuery confirm dialog with JSF
  • watir webdriver - window not found
  • Threads and Concurrent Modification Exception working with a list
  • content must have a ListView whose id attribute is 'android.R.id.list'
  • How to create subsets of a single set of elements with XSLT?
  • Neo4j…how to get a visual representation of my data?
  • How to specify generic type when the type is only known at runtime?
  • Android: Unable to detect vertical plane
  • Bitrate JWplayer
  • Excel VBA : conditional formatting of sheet1 cells from sheet2 values in excel 2007
  • Codeigniniter insert data through models and controller
  • Accessing Arguments, Workflow Variables from custom activities