获取当前的纬度和经度android [英] Get current latitude and longitude android

查看:122
本文介绍了获取当前的纬度和经度android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



有时(不是每次)我的经度和纬度都是0.0。



2.我想知道如何在用户通过设置启用gps后获取位置更新。



这是我的代码 p>

  public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// GPS状态标志
boolean isGPSEnabled = false;

//网络状态标志
boolean isNetworkEnabled = false;

// GPS状态标志
boolean canGetLocation = false;

位置位置; //位置
双纬度; //纬度
双经度; // longitude

//改变的最小距离以米为单位的更新
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10米

//以毫秒为单位的最小更新时间间隔
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1分钟

//声明位置管理器
受保护的LocationManager locationManager;

公共GPSTracker(上下文环境){
this.mContext = context;
getLocation();


public Location getLocation(){
try {
locationManager =(LocationManager)mContext
.getSystemService(LOCATION_SERVICE);

//获取GPS状态
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);

//获取网络状态
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if(!isGPSEnabled&&!isNetworkEnabled){
//没有启用网络提供者
} else {
this.canGetLocation = true;
if(isNetworkEnabled){
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
Log.d(网络,网络);
if(locationManager!= null){
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!= null){
latitude = location.getLatitude();
longitude = location.getLongitude();


$ b //如果启用GPS,使用GPS服务获得经纬度
if(isGPSEnabled){
if(location == null ){
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
Log.d(已启用GPS,已启用GPS);
if(locationManager!= null){
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!= null){
latitude = location.getLatitude();
longitude = location.getLongitude();





} catch(Exception e){
e.printStackTrace();
}

返回地点;

$ b $ ** b $ b *停止使用GPS监听器
*调用此函数将停止在您的应用中使用GPS
* * /
public void stopUsingGPS(){
if(locationManager!= null){
locationManager.removeUpdates(GPSTracker.this);


$ b $ ** b $ b *函数获得纬度
* * /
public double getLatitude(){
if(location!= null){
latitude = location.getLatitude();
}

//返回纬度
返回纬度;

$ b / **
*获得经度的函数
* * /
public double getLongitude(){
if(location! = null){
longitude = location.getLongitude();
}

//返回经度
返回经度;
}
$ b $ **
*检查GPS / wifi的功能
* @return boolean
* * /
public boolean canGetLocation (){
return this.canGetLocation;
}

/ **
*显示设置提示对话框的功能
*按下设置按钮后,将显示设置选项
* * /
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

//设置对话框标题
alertDialog.setTitle(GPS is settings);

//设置对话框消息
alertDialog.setMessage(GPS未启用,是否要进入设置菜单?);

//按设置按钮
alertDialog.setPositiveButton(Settings,新的DialogInterface.OnClickListener(){
public void onClick(DialogInterface对话框,int which){
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});

//按下取消按钮
alertDialog.setNegativeButton(取消,新的DialogInterface.OnClickListener(){
public void onClick(DialogInterface对话框,int其中){
dialog.cancel();
}
});

//显示提示信息
alertDialog.show();
}

@Override
public void onLocationChanged(Location location){
}

@Override
public void onProviderDisabled(字符串提供者){
}

@Override
public void onProviderEnabled(String provider){
}

@Override
public void onStatusChanged(String provider,int status,Bundle extras){
}

@Override
public IBinder onBind(Intent arg0){
return null;
}

}

像这样

  gps = new GPSTracker(this); 

//检查GPS是否启用
if(gps.canGetLocation()){

double latitude = gps.getLatitude();
double longitude = gps.getLongitude();

// \\\
是换行
Toast.makeText(getApplicationContext(),您的位置是 - \\\
Lat:+ latitude +\\\
Long:+ longitude ,Toast.LENGTH_LONG).show();
} else {
//无法获取位置
// GPS或网络未启用
//请求用户在设置中启用GPS /网络
gps .showSettingsAlert();


解决方案

href =http://gabesechansoftware.com/location-tracking/ =noreferrer> http://gabesechansoftware.com/location-tracking/ 。您正在使用的代码已经损坏。它不应该被使用。您看到的行为是其中一个错误 - 它不处理getLastLocation返回null的情况,这是预期的失败。它是由一个知道自己在做什么的人撰写的,但几年前它得到了高度评​​价,并将人们拧到今天。


Requirement:

1.Sometimes(not everytime) I am getting latitude and longitude 0.0.

2.I want to know how to get the location update after user has enabled the gps from the settings.

Here is my code

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }       
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}

From my activity class I am calling like this

 gps = new GPSTracker(this);

        // check if GPS enabled
        if(gps.canGetLocation()){

            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();

            // \n is for new line
            Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
        }else{
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gps.showSettingsAlert();
        }

解决方案

See my post at http://gabesechansoftware.com/location-tracking/. The code you're using is just broken. It should never be used. The behavior you're seeing is one of the bugs- it doesn't handle the case of getLastLocation returning null, an expected failure. It was written by someone who kind of knew what he was doing, but it got highly upvoted several years ago and screws people up to this day.

这篇关于获取当前的纬度和经度android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆