Android获取当前位置的问题

发布于 2024-10-30 14:33:31 字数 2152 浏览 4 评论 0原文

我想显示我当前位置的纬度和经度.. 为此,我没有在 Google 中搜索,而是在 SO 中搜索。

我只想显示我当前位置的纬度和经度。

请参阅下面的代码:

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;
    }

}

} 

我还在清单文件中添加了权限:

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

请参阅我得到的输出:

输入图像描述">

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 :

enter image description here

Where i am going wrong ? I dont understand, its a simple code and why its not working ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

安人多梦 2024-11-06 14:33:31

我刚刚验证了您的代码,它适用于这些更改,您只需将 tv.append() 调用移至 onLocationChanged() 方法,因为每次都会调用该方法,如果您不将其用于回调,那么您将仅获得第一个设置值,并且仅执行一次。

        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()));

        }

我已经在 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" />    

。您可以查看这些权限并过滤掉您不感兴趣的权限。我使用了从 此处

不过,我已经在 Android 2.2 上对其进行了测试,位置更新工作

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, Location Updates working

情魔剑神 2024-11-06 14:33:31

您在 Onlocationchanged 中获得了位置

 public void onLocationChanged(Location loc) {
    latitude = loc.getLatitude();
    longitude = loc.getLongitude();
    Log.i("MyLocation",Double.toString(latitude)+" "+Double.toString(longitude));
  }

,因此仅当当前位置发生更改时才会显示纬度和经度。为了检查,您提供一些纬度和经度并从 DDMS 中的模拟器控件发送,然后运行您的程序。当然它会显示的位置。

在此处输入图像描述

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.

enter image description here

佞臣 2024-11-06 14:33:31

如果您在设备中运行此程序,那么它会显示纬度和经度 0.0,直到我们更改位置。您必须从当前位置移动至少 10 米才能看到输出。因为如果不更改当前位置,onLocationChange() 方法不会触发,输出将为 0.0

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

孤独患者 2024-11-06 14:33:31

使用 LocationManager

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();

getLastKnownLocation() 的调用不会阻塞 - 这意味着如果当前没有可用位置,它将返回 null - 因此您可能想看看传递一个 < a href="http://developer.android.com/intl/de/reference/android/location/LocationListener.html" rel="nofollow">LocationListenerrequestLocationUpdates() 方法 代替,这将为您提供位置的异步更新。

private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        longitude = location.getLongitude();
        latitude = location.getLatitude();
    }
}

lm.requestLocationUpdates(LocationManager.GPS, 2000, 10, locationListener);

您需要为您的应用程序提供 ACCESS_FINE_LOCATION如果您想使用 GPS,请获得 权限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

您可能还需要添加 ACCESS_COARSE_LOCATION 权限(当 GPS 不可用时),并使用 getBestProvider () 方法

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.

日久见人心 2024-11-06 14:33:31

我认为使用模拟器你无法获得 GPS 坐标。如果您使用移动设备,请在建筑物外尝试使用 GPS。有时您无法获得建筑物内的 GPS 坐标。如果那次你也失败了,那么我将发布我们成功的代码。

下面的代码刚刚我已经测试过了,它对我有用。

 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 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..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文