How to get user location
- Home
- chevron_right
- Solutions
- chevron_right
- How to get user location
Nowadays, knowing the location is very important for applications. Even if you want to develop a simple application that returns the coordinates, or you develop different kind of apps that need location and you need to know what is the location of the use,r this tutorial might help you.
In order to get your current location (latitude and longitude) you have to follow this steps:
1. In your AndroidManifest.xml file you have to add this permission just before manifest tag () closes like in the example below:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"> </uses-permission>
2. You have to create a class (the class in this example will be called let’s say… MyCurrentLoctionListener) which implements LocationListener. You will have to implement now all the methods from LocationListener like in this example:
public class MyCurrentLoctionListener implements LocationListener{ @Override public void onLocationChanged(Location location) { location.getLatitude(); location.getLongitude(); String myLocation = "Latitude = " + location.getLatitude() + " Longitude = " + location.getLongitude(); //I make a log to see the results Log.e("MY CURRENT LOCATION", myLocation ) } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }
3. And now in your main class in OnCreate() method you have to add this code:
//get Your Current Location LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); MyCurrentLoctionListener locationListener = new MyCurrentLoctionListener(); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
4. Now you can test this using a phone or using the emulator. If you use the emulator you have three options to test:
- USING TELNET: open cmd from Windows Start -> Search -> cmd and write the following commands (nothing else except the coordinates 120 and 118 of course 🙂 ):
- telnet localhost 5554
- geo fix 120 118
In the last command 120 and 118 represent the coordinates (Latitude and Longitude).
But if these commands don’t work for you, it might be because you don’t have telnet feature. So to turn it on, you have to go to ControlPanel – Unistal a program – and click on the left side on Turn Windows Features On or OFF. Now here you must have Telnet features, click on them and then press the OK button. Now you will be able to use the above commands and test this code.
2. USING DDMS: go where is your Android folder installed – open the tools folder – double click on ddms.bat. Now that ddms is open you have to click on the emulator tab like in the picture below:
And now go to the Eumulator Control tab, scroll down and you will see the Location Controls where you can set Latitude and Logitude.