LatLng返回0,0 [英] LatLng return 0,0

查看:117
本文介绍了LatLng返回0,0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个显示我当前位置的应用程序
我拥有所有的功能,
我有另一个类名称的GPS跟踪器来获取我的GPS位置



继承人我的代码:

  GPSTracker gpsTracker = new GPSTracker(this); 
LocationManager lm =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,this);
map =((MapFragment)getFragmentManager()。findFragmentById(R.id.map))。getMap();
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
latitude = gpsTracker.latitude;
longitude = gpsTracker.longitude;
LatLng latLng =新LatLng(经度,纬度);
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(18));

以下是GPSTracker类:​​

  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 $ **
*停止使用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追踪器类别。这是可怕的可怕的破碎。在很多方面,我今晚写了一篇关于它的长篇博文:请参阅 http://gabesechansoftware.com/location-tracking /



以下是破碎的方式:

1)它不跟踪GPS。有时它跟踪网络位置而不是

<2> CanGetLocation功能已损坏。它在它有一个位置之前返回true



<3>它的效率非常低,迫使你投票。



4 )它不会区分陈旧和新鲜的数据,也不会让你做到这一点。



我会继续,但我已经写了它今晚。

我在我的博客上写了一个更好的GPS追踪器库。这里重复使用

LocationTracker.java
$ b

 包com.gabesechan.android.reusable.location; 

导入android.location.Location;

public interface LocationTracker {
public interface LocationUpdateListener {
public void onUpdate(Location oldLoc,long oldTime,Location newLoc,long newTime);
}

public void start();
public void start(LocationUpdateListener update);

public void stop();

public boolean hasLocation();

public boolean hasPossiblyStaleLocation();

public Location getLocation();

public Location getPossiblyStaleLocation();


$ / code>

ProviderLocationTracker.java

  package com.gabesechan.android.reusable.location; 

导入android.content.Context;
导入android.location.Location;
导入android.location.LocationListener;
导入android.location.LocationManager;
导入android.os.Bundle;

public class ProviderLocationTracker实现LocationListener,LocationTracker {

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

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

私人LocationManager lm;

public enum ProviderType {
NETWORK,
GPS
};
私有字符串提供程序;

私人位置lastLocation;
私人长期lastTime;

私人布尔isRunning;

私人LocationUpdateListener侦听器;

public ProviderLocationTracker(Context context,ProviderType type){
lm =(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
if(type == ProviderType.NETWORK){
provider = LocationManager.NETWORK_PROVIDER;
}
else {
provider = LocationManager.GPS_PROVIDER;


$ b $ public void start(){
if(isRunning){
//已经运行,什么也不做
return;
}

//提供商已开启,因此开始获取更新。更新当前位置
isRunning = true;
lm.requestLocationUpdates(提供者,MIN_UPDATE_TIME,MIN_UPDATE_DISTANCE,this);
lastLocation = null;
lastTime = 0;
return;
}

public void start(LocationUpdateListener update){
start();
listener = update;



$ b public void stop(){
if(isRunning){
lm.removeUpdates(this);
isRunning = false;
listener = null;



public boolean hasLocation(){
if(lastLocation == null){
return false;
}
if(System.currentTimeMillis() - lastTime> 5 * MIN_UPDATE_TIME){
return false; //过期
}
返回true;


public boolean hasPossiblyStaleLocation(){
if(lastLocation!= null){
return true;
}
返回lm.getLastKnownLocation(provider)!= null;

$ b $ public Location getLocation(){
if(lastLocation == null){
return null;
}
if(System.currentTimeMillis() - lastTime> 5 * MIN_UPDATE_TIME){
return null; //过期
}
返回lastLocation;

$ b $ public Location getPossiblyStaleLocation(){
if(lastLocation!= null){
return lastLocation;
}
return lm.getLastKnownLocation(provider);
}

public void onLocationChanged(Location newLoc){
now now = System.currentTimeMillis();
if(listener!= null){
listener.onUpdate(lastLocation,lastTime,newLoc,now);
}
lastLocation = newLoc;
lastTime = now;
}

public void onProviderDisabled(String arg0){

}

public void onProviderEnabled(String arg0){


$ b $ public void onStatusChanged(String arg0,int arg1,Bundle arg2){
}





FallbackLocationTracker.java

  package com.gabesechan.android.reusable.location; 

导入android.content.Context;
导入android.location.Location;
导入android.location.LocationManager;

public class FallbackLocationTracker实现LocationTracker,LocationTracker.LocationUpdateListener {


private boolean isRunning;

私人ProviderLocationTracker gps;
私人ProviderLocationTracker净;

私人LocationUpdateListener侦听器;

位置lastLoc;
long lastTime;

public FallbackLocationTracker(Context context,ProviderLocationTracker.ProviderType type){
gps = new ProviderLocationTracker(context,ProviderLocationTracker.ProviderType.GPS);
net = new ProviderLocationTracker(context,ProviderLocationTracker.ProviderType.NETWORK);
}
$ b $ public void start(){
if(isRunning){
//已经运行,什么都不做
return;
}

//开始
gps.start(this);
net.start(this);
isRunning = true;
}

public void start(LocationUpdateListener update){
start();
listener = update;



public void stop(){
if(isRunning){
gps.stop();
net.stop();
isRunning = false;
listener = null;



public boolean hasLocation(){
//如果有一个位置,使用它
return gps.hasLocation()|| net.hasLocation();
}

public boolean hasPossiblyStaleLocation(){
//如果有一个位置,使用它
return gps.hasPossiblyStaleLocation()|| net.hasPossiblyStaleLocation();


public Location getLocation(){
Location ret = gps.getLocation();
if(ret == null){
ret = net.getLocation();
}
return ret;
}

public Location getPossiblyStaleLocation(){
Location ret = gps.getPossiblyStaleLocation();
if(ret == null){
ret = net.getPossiblyStaleLocation();
}
return ret;


public void onUpdate(Location oldLoc,long oldTime,Location newLoc,long newTime){
boolean update = false;

//只有当没有最后一个位置,提供者是相同的,或者提供者更准确,或者旧位置是陈旧的时,我们才应该更新
if(lastLoc == null ){
update = true;

else if(lastLoc!= null&&&& lastLoc.getProvider()。equals(newLoc.getProvider())){
update = true;
}
else if(newLoc.getProvider()。equals(LocationManager.GPS_PROVIDER)){
update = true;
}
else if(newTime - lastTime> 5 * 60 * 1000){
update = true;
}

if(update){
lastLoc = newLoc;
lastTime = newTime;
if(listener!= null){
listener.onUpdate(lastLoc,lastTime,newLoc,newTime);
}
}

}


}

界面定义了一个通用位置跟踪器,因此您可以在它们之间切换。 ProviderLocationTracker将允许您通过GPS或网络进行跟踪,具体取决于您传递给其构造函数的参数。 FallbackLocationTracker将通过两者进行跟踪,只给出当前可用的最准确信息,但如果GPS尚未准备好,则会返回到网络。


I am trying to create an app that shows my current location I have all the permisson neccessary, I have another class name GPS tracker to get my gps locations

Heres my code :

GPSTracker gpsTracker = new GPSTracker(this);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
latitude = gpsTracker.latitude;
longitude = gpsTracker.longitude;
LatLng latLng = new  LatLng(latitude, longitude);
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(18));

Here is the GPSTracker class:

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;
            // First get location from Network Provider
            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;
}

}

解决方案

DO NOT USE THE GPS TRACKER CLASS. It's horribly horribly broken. In so many ways I wrote a long blog post about it tonight: see http://gabesechansoftware.com/location-tracking/

Here's the ways its broken:

1)It doesn't track GPS. Sometimes it tracks network location instead

2)The canGetLocation function is broken. It returns true before it has a location

3)Its horribly inefficient, forcing you to poll.

4)It doesn't differentiate stale from fresh data- and doesn't let you do it either

I'd go on but I already wrote it up tonight.

I wrote a much better GPS tracker library at my blog. Here it is repeated for SO use

LocationTracker.java

package com.gabesechan.android.reusable.location;

import android.location.Location;

public interface LocationTracker {
    public interface LocationUpdateListener{
        public void onUpdate(Location oldLoc, long oldTime, Location newLoc, long newTime);
    }

    public void start();
    public void start(LocationUpdateListener update);

    public void stop();

    public boolean hasLocation();

    public boolean hasPossiblyStaleLocation();

    public Location getLocation();

    public Location getPossiblyStaleLocation();

}

ProviderLocationTracker.java

package com.gabesechan.android.reusable.location;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class ProviderLocationTracker implements LocationListener, LocationTracker {

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

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

    private LocationManager lm;

    public enum ProviderType{
        NETWORK,
        GPS
    };    
    private String provider;

    private Location lastLocation;
    private long lastTime;

    private boolean isRunning;

    private LocationUpdateListener listener;

    public ProviderLocationTracker(Context context, ProviderType type) {
        lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        if(type == ProviderType.NETWORK){
            provider = LocationManager.NETWORK_PROVIDER;
        }
        else{
            provider = LocationManager.GPS_PROVIDER;
        }
    }

    public void start(){
        if(isRunning){
            //Already running, do nothing
            return;
        }

        //The provider is on, so start getting updates.  Update current location
        isRunning = true;
        lm.requestLocationUpdates(provider, MIN_UPDATE_TIME, MIN_UPDATE_DISTANCE, this);
        lastLocation = null;
        lastTime = 0;
        return;
    }

    public void start(LocationUpdateListener update) {
        start();
        listener = update;

    }


    public void stop(){
        if(isRunning){
            lm.removeUpdates(this);
            isRunning = false;
            listener = null;
        }
    }

    public boolean hasLocation(){
        if(lastLocation == null){
            return false;
        }
        if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
            return false; //stale
        }
        return true;
    }

    public boolean hasPossiblyStaleLocation(){
        if(lastLocation != null){
            return true;
        }
        return lm.getLastKnownLocation(provider)!= null;
    }

    public Location getLocation(){
        if(lastLocation == null){
            return null;
        }
        if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
            return null; //stale
        }
        return lastLocation;
    }

    public Location getPossiblyStaleLocation(){
        if(lastLocation != null){
            return lastLocation;
        }
        return lm.getLastKnownLocation(provider);
    }

    public void onLocationChanged(Location newLoc) {
        long now = System.currentTimeMillis();
        if(listener != null){
            listener.onUpdate(lastLocation, lastTime, newLoc, now);
        }
        lastLocation = newLoc;
        lastTime = now;
    }

    public void onProviderDisabled(String arg0) {

    }

    public void onProviderEnabled(String arg0) {

    }

    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    }




}

FallbackLocationTracker.java

package com.gabesechan.android.reusable.location;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;

public class FallbackLocationTracker  implements LocationTracker, LocationTracker.LocationUpdateListener {


    private boolean isRunning;

    private ProviderLocationTracker gps;
    private ProviderLocationTracker net;

    private LocationUpdateListener listener;

    Location lastLoc;
    long lastTime;

    public FallbackLocationTracker(Context context, ProviderLocationTracker.ProviderType type) {
        gps = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.GPS);
        net = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.NETWORK);
    }

    public void start(){
        if(isRunning){
            //Already running, do nothing
            return;
        }

        //Start both
        gps.start(this);
        net.start(this);
        isRunning = true;
    }

    public void start(LocationUpdateListener update) {
        start();
        listener = update;
    }


    public void stop(){
        if(isRunning){
            gps.stop();
            net.stop();
            isRunning = false;
            listener = null;
        }
    }

    public boolean hasLocation(){
        //If either has a location, use it
        return gps.hasLocation() || net.hasLocation();
    }

    public boolean hasPossiblyStaleLocation(){
        //If either has a location, use it
        return gps.hasPossiblyStaleLocation() || net.hasPossiblyStaleLocation();
    }

    public Location getLocation(){
        Location ret = gps.getLocation();
        if(ret == null){
            ret = net.getLocation();
        }
        return ret;
    }

    public Location getPossiblyStaleLocation(){
        Location ret = gps.getPossiblyStaleLocation();
        if(ret == null){
            ret = net.getPossiblyStaleLocation();
        }
        return ret;
    }

    public void onUpdate(Location oldLoc, long oldTime, Location newLoc, long newTime) {
        boolean update = false;

        //We should update only if there is no last location, the provider is the same, or the provider is more accurate, or the old location is stale
        if(lastLoc == null){
            update = true;
        }
        else if(lastLoc != null && lastLoc.getProvider().equals(newLoc.getProvider())){
            update = true;
        }
        else if(newLoc.getProvider().equals(LocationManager.GPS_PROVIDER)){
            update = true;
        }
        else if (newTime - lastTime > 5 * 60 * 1000){
            update = true;
        }

        if(update){
            lastLoc = newLoc;
            lastTime = newTime;
            if(listener != null){
                listener.onUpdate(lastLoc, lastTime, newLoc, newTime);                  
            }
        }

    }


}

The interface defines a generic location tracker so you can switch between them. ProviderLocationTracker will allow you to track via GPS or network, depending on the parameter you pass to its constructor. FallbackLocationTracker will track via both, giving you only the most accurate info currently available but falling back to network if GPS isn't ready.

这篇关于LatLng返回0,0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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