Get latitude,longitude without touch - android

How to find user current location latitude,longitude without touch event?I searched in internet but i get latitude,longitude only touch event.

I've answered to similar question of yours here. Take a look at that. It doesn't need the google maps.
public class LocationSampleActivity extends Activity implements OnInitListener
{
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)this.findViewById(R.id.txtLocation);
tts = new TextToSpeech(this, this);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll);
}
private class mylocationlistener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
String str = "\n CurrentLocation: "+
"\n Latitude: "+ location.getLatitude() +
"\n Longitude: " + location.getLongitude();
tv.append(str);
speak(location);
}
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(LocationSampleActivity.this,"Error onProviderDisabled",Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(LocationSampleActivity.this,"onProviderEnabled",Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(LocationSampleActivity.this,"onStatusChanged",Toast.LENGTH_LONG).show();
}
}
}
It will update your current location's latitude & longtitude into the TextView without touch simply. Please add the important permission into your manifest file.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

use MyLocationOverlay for get current location.
MyLocationOverlay whereAmI = new MyLocationOverlay(this,mapview);
GeoPoint myLocationGeoPoint = whereAmI.getMyLocation();
float latitude = myLocationGeoPoint.getLatitudeE6() / 1E6;
float longitude = myLocationGeoPoint.getLongitudeE6() / 1E6;

Related

Android location loop

I'm using the following code to get the users location:
public class MainActivity extends ActionBarActivity {
//=========================================== On Create ========================================
#
Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//======================================= Location =========================================
LocationManager mlocManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
}
public class MyLocationListener implements LocationListener {#
Override
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " +
"Latitude = " + loc.getLatitude() +
"Longitude = " + loc.getLongitude();
Toast.makeText(getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();
}#
Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(),
"Gps Disabled",
Toast.LENGTH_SHORT).show();
}#
Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(),
"Gps Enabled",
Toast.LENGTH_SHORT).show();
}#
Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
When I run the app, it goes into an endless loop of displaying me the location of the user. How can I make it show location only once with a click of a button?
Edited the code below to use either GPS or Network location.
Also use these permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
Here is a very simple case, a UI with just a Button and a TextView.
MainActivity.java:
public class MainActivity extends ActionBarActivity {
Button button;
TextView locText;
double lat;
double lon;
Location loc;
LocationManager mlocManager;
String provider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.buttonGo);
locText = (TextView)findViewById(R.id.textView);
mlocManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
//LocationListener mlocListener = new MyLocationListener();
//mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
Criteria criteria = new Criteria();
//criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAccuracy(Criteria.ACCURACY_COARSE); //Try this instead
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = mlocManager.getBestProvider(criteria, true);
if (provider != null) {
loc = mlocManager.getLastKnownLocation(provider);
lat = loc.getLatitude();
lon = loc.getLongitude();
}
locText.setText(lat + " " + lon);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (provider != null) {
loc = mlocManager.getLastKnownLocation(provider);
lat = loc.getLatitude();
lon = loc.getLongitude();
}
locText.setText(lat + " " + lon);
}
});
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:id="#+id/buttonGo"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Refresh Location"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_below="#+id/buttonGo"
android:layout_marginTop="86dp" />
</RelativeLayout>

Can't get latitude and Longitude

I tried to get latitude and longitude for current location.
However, when I use the code below, the location listener is not triggered at all.
I've added the LOCATION permission in manifest file.
anyone can help?
Here is the java code:
package com.example.setlocaction;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends Activity{
double latitude, longitude, radius;
LocationManager mlocManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Acquire a reference to the system Location Manager
mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener()
{
public void onLocationChanged(Location loc)
{
// Called when a new location is found by the network location provider.
Log.i("loc","location changed");
if (loc!=null)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " +
"Latitud =" + loc.getLatitude() +
"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
}
}
public void onStatusChanged(String provider, int status, Bundle extras)
{}
public void onProviderEnabled(String provider)
{}
public void onProviderDisabled(String provider)
{}
};
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
// 高精度
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = mlocManager.getBestProvider(criteria, true);
mlocManager.requestLocationUpdates(provider, 2000, 0, locationListener);
Location loc=mlocManager.getLastKnownLocation(provider);
if (loc==null)
{
Log.i("loc","loc=null");
}
}
}
mafinest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.setlocaction"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.setlocaction.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
First of all, your current solution utilizes "getLastKnownLocation" which means, that if you actually retrieve the longitude and latitude, you cannot be certain that it will return the current position of the user. It simply returns the location which was last found which can be miles away.
That is nothing wrong in doing so, but it leaves for uncertainty.
Instead, I have personally implemented a location manager for retrieving the current position of the user by utilizing the code provided in the following post which works great:
https://stackoverflow.com/a/17290348/2399772
By using this specific code, you will also be given the advantage that it tries to utilize the WiFi connection first for determining the position which is slightly better. It that doesn't work, it will utilize the GPS instead. Additionally, if GPS services aren't enabled, a dialogue will be shown telling the user to enable those.
Hope this helps.
Additional notes
As I have stated in a previous post, the Geolocation API will does unfortunately not work on all devices. You can hereby consider using the Reverse Geocoding API instead, which is additionally much more reliable:
https://developers.google.com/maps/documentation/geocoding/
It simply requires that you send a HTTP request which should contain latitude and longitude, whereafter it will provide a response in JSON which is easily parsed.
Sometimes it takes a while for the device to deliver the first locations if you haven't used the GPS before. Also, make sure you're in a location where you can gps updates, or try on the emulator using geo fix via telnet.
try this
public class MyLocationActivity extends Activity implements LocationListener {
private LocationManager mgr;
private String best;
public static double myLocationLatitude;
public static double myLocationLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
dumpProviders();
Criteria criteria = new Criteria();
best = mgr.getBestProvider(criteria, true);
Log.d("best provider", best);
Location location = mgr.getLastKnownLocation(best);
dumpLocation(location);
//may be some intent here
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
dumpLocation(location);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
protected void onPause() {
super.onPause();
mgr.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
mgr.requestLocationUpdates(best, 15000, 1, this);
}
private void dumpLocation(Location l) {
if (l == null) {
myLocationLatitude = 0.0;
myLocationLongitude = 0.0;
} else {
myLocationLatitude = l.getLatitude();
myLocationLongitude = l.getLongitude();
}
}
private void dumpProviders() {
List<String> providers = mgr.getAllProviders();
for (String p : providers) {
dumpProviders(p);
}
}
private void dumpProviders(String s) {
LocationProvider info = mgr.getProvider(s);
StringBuilder builder = new StringBuilder();
builder.append("name: ").append(info.getName());
}
}
Add following code to your java file
private void GetLocation()
{
LocationDetail pref_LocationDetail = new LocationDetail(_context);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(objCommon.isOnline(_context))
{
if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER ,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
return ;
}
else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER ,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
return ;
}
}
}
private class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location location)
{
LocationDetail pref_LocationDetail = new LocationDetail(_context);
double Lattitude = location.getLatitude();
double Longitude = location.getLongitude();
Toast.makeText(_context , location.getProvider().toString() , Toast.LENGTH_LONG).show();
locationManager.removeUpdates(this);
locationManager = null;
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(_context , "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(_context ,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(_context ,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
just add following code in your manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />

Location is displaying as null when using LocationManager

I want to get current location's latitude and longitude. I used LocationManager for this, but it is displaying location as null and latitude and longitude as 0.0. I have used required permissions in manifest and GPS connection.
Code:
LocationdemoActivity.java:
public class LocationdemoActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
Button buttonLocation = (Button) findViewById(R.id.buttonLocation);
buttonLocation.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(
getApplicationContext(),
"loc:" + MyLocationListener.location + "latitude "
+ MyLocationListener.latitude + "longitude "
+ MyLocationListener.longitude, 5000).show();
}
});
}
}
MyLocationListener.java:
public class MyLocationListener implements LocationListener {
public static double latitude;
public static double longitude;
public static Location location;
#Override
public void onLocationChanged(Location loc)
{
location = loc;
loc.getLatitude();
loc.getLongitude();
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
protected boolean isRouteDisplayed() {
return false;
}
}
Permissions in manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES"/>
What is the problem?
Try to do something like this
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,mlocListener);
location = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Button buttonLocation = (Button) findViewById(R.id.buttonLocation);
buttonLocation.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(getApplicationContext(),
"loc:" + location + "latitude "
+ location.latitude + "longitude "
+ location.longitude, 5000).show();
}
});

GPS - getting lat and longitude in android

I am using following code to get current latitude and longitude. But none of the toasts are displayed.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
Log.i("","loccccccccccc");
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " + "Latitud = " + loc.getLatitude() + "Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
} }
}
used all the permissions:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
<uses-permission android:name="android.permission.INTERNET" />
Thanks for the help in advance
Sneha
GPS doesn't work in indoor mode..depending upon the place..It works perfectly on outdoor mode..So check it out outside..
GPS_PROVIDER is slow when compared to The NETWORK_PROVIDER.And in room it may not work.Switch on the GPS if you want to use GPS_PROVIDER. or else use NETWORK_PROVIDER.
Go through this
Note:Network_provider is not so accurate compared to the GPS_Provider.. But it is fast..
See this link also
#Sneha --
1) is this line printed Log.i("","loccccccccccc");
2) Check this
3) try to use criteria
4) Test this on mobile (Device) & also test it outside as GPS doesn't work inside.

Problem in Getting the Current Location in Android

I want to display latitude and longitude my current location..
For this rather than searching in Google, i searched in SO.
I just want to display my current location latitude and longitude.
See my code below :
public class LocationGetter extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
LocationManager mlocManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new LocationManagerHelper();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 100,mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
tv.append("Latitude:- " + LocationManagerHelper.getLatitude()
+ '\n');
tv.append("Longitude:- " + LocationManagerHelper.getLongitude()
+ '\n');
Log.i("MyLocation1",Double.toString(LocationManagerHelper.getLatitude())+" "+Double.toString(LocationManagerHelper.getLongitude()));
} else {
tv.setText("GPS is not turned on...");
}
/** set the content view to the TextView */
setContentView(tv);
}
/* Class My Location Listener */
public static class LocationManagerHelper implements LocationListener {
private static double latitude;
private static double longitude;
#Override
public void onLocationChanged(Location loc) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("MyLocation",Double.toString(latitude)+" "+Double.toString(longitude));
}
#Override
public void onProviderDisabled(String provider) { }
#Override
public void onProviderEnabled(String provider) { }
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public static double getLatitude() {
return latitude;
}
public static double getLongitude() {
return longitude;
}
}
}
I have also added permission in manifest file :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
See the output i am getting :
Where i am going wrong ? I dont understand, its a simple code and why its not working ?
I just verified your code and it works with these changes, you just need to move the tv.append() calls to the onLocationChanged() method as that is called each time, if you don't use that for the CallBack, then u will get the first set values only and it's only executed once.
public void onLocationChanged(Location loc) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("MyLocation",Double.toString(latitude)+" "+Double.toString(longitude));
tv.append("Latitude:- " + LocationManagerHelper.getLatitude()
+ '\n');
tv.append("Longitude:- " + LocationManagerHelper.getLongitude()
+ '\n');
Log.i("MyLocation1",Double.toString(LocationManagerHelper.getLatitude())+" "+Double.toString(LocationManagerHelper.getLongitude()));
}
and I have used these permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
You can look at these and filter out the ones you won't be interested in. I have used a downloaded .gpx file from here
I've tested it on Android 2.2 though,
You got location in Onlocationchanged
public void onLocationChanged(Location loc) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.i("MyLocation",Double.toString(latitude)+" "+Double.toString(longitude));
}
so the lattitude and longitude will be displayed only when the change from the current location.for checking you give some latitude and longitude and send from your emulator control in DDMS and after that you run your program.Sure it will show the location.
If you run this program in device then it show latitude and longitude 0.0 until we change our position.You must move at least 10 meter from your current position to see the output. Because without change current position onLocationChange() method does not fire and output will be 0.0
Use the LocationManager.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
lm.requestLocationUpdates(LocationManager.GPS, 2000, 10, locationListener);
You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.
I think with the emulator you can't get the GPS co-ordinates. If you are working with the mobile, try the GPS outside of your building. sometimes you won't get the GPS co-ordinates inside the building. If that time also you failed, then i will post the code that we got succeeded.
The below code just now i have tested and its works for me..
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class GetGPS extends Activity {
String GPSPROVIDER = LocationManager.GPS_PROVIDER;
private static final long MIN_GEOGRAPHIC_POOLING_TIME_PERIOD = 10000;
private static final float MIN_GEOGRAPHIC_POOLING_DISTANCE = (float)5.0;
public LocationManager gpsLocationManager;
static Context context = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
/*Get a listener for GPS*/
LocationListener gpsLocationListener = null;
gpsLocationListener = new GpsLocationListener(this);
/*Start Location Service for GPS*/
gpsLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
/*Register GPS listener with Location Manager*/
gpsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_GEOGRAPHIC_POOLING_TIME_PERIOD,
MIN_GEOGRAPHIC_POOLING_DISTANCE, gpsLocationListener);
boolean isavailable = gpsLocationManager.isProviderEnabled(GPSPROVIDER);
if(isavailable) {
Location loc = gpsLocationManager.getLastKnownLocation("gps");
if(loc != null) {
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
Toast.makeText(GetGPS.this,"Longitude is "+longitude + " Latitude is "+latitude, Toast.LENGTH_LONG).show();
}
}
}
public static class GpsLocationListener implements LocationListener {
public GpsLocationListener(Context context){
}
public void onLocationChanged(Location loc) {
if (loc != null) {
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
Toast.makeText(context,"Longitude is "+longitude + " Latitude is "+latitude, Toast.LENGTH_LONG).show();
}
}//End of onLocationChanged Method
#Override
public void onProviderDisabled(String provider) {
}//End of onProviderDisabled Method
#Override
public void onProviderEnabled(String provider) {
}//End of onProviderEnabled Method
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}//End of onStatusChanged Method
}//End of GpsLocationListener class
}
I tested this by moving the device from one place to another...
I hope it will helps..

Categories

Resources