【问题标题】:Android- Get current location but latitude and longitude return 0.0 (make wrong calculation)Android-获取当前位置但经纬度返回0.0(计算错误)
【发布时间】:2014-02-08 04:42:43
【问题描述】:

我正在尝试制作一个简单的程序来执行将显示在列表视图中的距离计算。我使用来自 androidhive 的 GPSTracker,并为我的列表活动调用纬度和经度

public class GPSTracker extends Service implements LocationListener {

private final Context mContext;
boolean isGPSEnabled =false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double 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);
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if(!isGPSEnabled&& !isNetworkEnabled){
            //no network enable
        }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(isGPSEnabled){
                if(location == null){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    if(location != null){
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
        }

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

public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);

    }
}

public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }
    return latitude;
}

public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();

    }
    return longitude;
}

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) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}
}

还有我的列表活动

public class Mobil extends ListFragment implements LocationListener{
GPSTracker gps;
private static final String url = "http://10.0.2.2/tambalban/car.php";  

JSONArray tambalban = null;
ArrayList<HashMap<String, String>> listMobil = new ArrayList<HashMap<String, String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);             
    new getJSONData().execute();        
}

public class getJSONData extends
        AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {

    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(
            String... params) {

        JSONParser jParser = new JSONParser();
        JSONObject json = jParser.getJSONFromURL(url);

        gps = new GPSTracker(getActivity()); // is it right calling from GPSTracker?    
        double lat_user = gps.getLatitude(); // get latitude, right?
        double lng_user = gps.getLongitude();
        System.out.println("lat_user : "+lat_user+""); // print in logcat return 0.00
        System.out.println("lng_user : "+lng_user+"");// print in logcat return 0.00    

        try {
            tambalban = json.getJSONArray(TAG_TAMBALBAN);

            for (int i = 0; i < tambalban.length(); i++) {
                JSONObject mtr = tambalban.getJSONObject(i);

                 String id_tb = mtr.getString(TAG_ID);
                 String name_tb = mtr.getString(TAG_NAMA);
                 String address_tb = mtr.getString(TAG_ALAMAT);
                 String telp_tb = mtr.getString(TAG_TELP);
                 String lat = mtr.getString(TAG_LAT);
                 String lng = mtr.getString(TAG_LNG);

                 double lat_tujuan = Double.parseDouble(lat);
                 double lng_tujuan = Double.parseDouble(lng);
                         double distance = hitungJarak(lat_user, lng_user, lat_tujuan, lng_tujuan);
                 distance = RoundDecimal(distance, 2);
                 String dist = Double.toString(distance)+" km";

                 HashMap<String, String> a = new HashMap<String, String>();

                a.put(TAG_ID, id_tb);
                a.put(TAG_NAMA, name_tb);
                a.put(TAG_ALAMAT, address_tb);
                a.put(TAG_TELP, telp_tb);
                a.put(TAG_LAT, lat);
                a.put(TAG_LNG, lng);
                a.put(TAG_JARAK, dist);

                listMobil.add(a);                       
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return listMobil;

    }

private double RoundDecimal(double distance, int i) {
        BigDecimal bd = new BigDecimal(distance);
        bd = bd.setScale(i, 6);         
        return bd.doubleValue();
    }


private double hitungJarak(double lat_user, double lng_user,
            double lat_tujuan, double lng_tujuan) {
    double dist;
    double radius = 6371;
    double dLat = Math.toRadians(lat_tujuan - lat_user);
    double dLon = Math.toRadians(lng_tujuan- lng_user);
    double a = Math.sin(dLat/2) * Math.sin(dLat /2)
            + Math.cos(Math.toRadians(lat_user)) * Math.cos(Math.toRadians(lat_tujuan)) 
            * Math.sin(dLon/ 2) * Math.sin(dLon/2);

    double c = 2 * Math.asin(Math.sqrt(a));
    double valueResult = radius * c;
    double km = valueResult/1;
    DecimalFormat newFormat = new DecimalFormat("####");
    int kmInDec = Integer.valueOf(newFormat.format(km));

    dist = radius * c;

        return dist;
    }


    @Override
    protected void onPostExecute(
            ArrayList<HashMap<String, String>> listMobil) {
        // TODO Auto-generated method stub
        super.onPostExecute(listMobil);
        ListAdapter adapter = new SimpleAdapter(getActivity(), listMobil,
                R.layout.list_item, new String[] { TAG_NAMA, TAG_ALAMAT, TAG_JARAK },
                new int[] { R.id.namatb, R.id.alamattb,R.id.jarak });
        setListAdapter(adapter);        
    }

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return inflater.inflate(R.layout.list_fragment, container, false);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub

    super.onListItemClick(l, v, position, id);
    String pilih = getListAdapter().getItem(position).toString();
    Toast.makeText(getActivity(),
            pilih,
            Toast.LENGTH_LONG).show();



    Intent i = new Intent(getActivity(), DetailDaftar.class);
    Bundle bundle = new Bundle();
    bundle.putString("Selected", pilih);


    i.putExtras(bundle);
    startActivity(i); 
}

@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}   
}

我使用 Sytem.out.println 检查,纬度和经度都返回 0.00。 我打电话给当前位置错了吗?感谢您的帮助。

【问题讨论】:

  • 您是否在 manifest.xml 文件中添加了权限&lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /&gt;
  • 感谢您的回复,我之前已经在清单中添加了权限,但它仍然没有得到 lat 和 lng
  • @Bambang:也许您只启用了 GPS 选项并禁用了网络和 wifi 选项,并且您试图在室内访问 GPS 位置。如果你这样做,你只会得到 0.0 两者。看看这个!

标签: android listview latitude-longitude currentlocation


【解决方案1】:

您应该在 AsyncTask 之外创建您的 GPSTracker gps 对象,尝试如下:

 @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);    
gps = new GPSTracker(getActivity()); // is it right calling from GPSTracker?             
new getJSONData().execute();        

}

并将所需的permission 添加到您的manifest.xml 文件中:

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

【讨论】:

  • 感谢您的回复,确定我已经添加了这些权限。我尝试在 onCreate 中移动 GPSTracker,但仍然没有得到 lat 和 lng
【解决方案2】:

您的 GPSTracker 类将返回当前位置的纬度和经度。我已经检查过了,它正在返回纬度/经度值。 在第二部分我没有得到,你想用 json 做什么,但如果你想在另一个活动中获得纬度经度,那么只需实例化 GPSTracker 类就像

内部活动

GPSTracker 跟踪器;

onCreate方法里面

tracker=new GPSTracker(this);

还有一件事 ypu 不能在 doInBackground() 方法中打印或记录任何语句,因为它只会在后台运行。 尝试用onPostExecute() 方法来祝酒你的输出

【讨论】:

  • 我已经在 onCreate 中移动 GPSTracker,但仍然没有得到 lat 和 lng。关于打印它的工作伙伴。
【解决方案3】:

如果您使用模拟器进行测试,那么您应该执行以下操作:

1.在你的编辑器中(我假设你使用的是 Eclipse)去

Window -> Open Perspective -> Show View -> Emulator Control.

2 你会看到两个带有标签“纬度”和“经度”的可编辑文本框。

3 适当设置值并单击发送。

现在您的模拟器具有您设置的值。

【讨论】:

  • 我从来没有成功用DDMS添加lat和lng,我用putty输入telnet命令,你有什么想法吗?我也觉得我的模拟器可能出错了
【解决方案4】:

这是我获取 Longitude 和 Latitude 的代码,它对我很有用

public void setLocation() { 
            LocationManager LM;

    LM = (LocationManager) CurrentContext
            .getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
            // adjust ur criteria with ur desired features

    provider = LM.getBestProvider(criteria, true);

    try {

        LM.requestLocationUpdates(provider, 1000, 1, this);

        if (LM != null) {
            Loc = LM.getLastKnownLocation(provider);

            if (Loc != null) {
                userLocation = new Location("");

                userLocation.setLatitude(Loc.getLatitude());
                userLocation.setLongitude(Loc.getLongitude());

            }
        }

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

    LM.removeUpdates(this);
}

【讨论】:

  • 嗨伙计,它仍然不能解决我的问题,我对 ListFragment 很好奇,当我使用 listFragment 代替 Activity 时是否正确
  • 无论你使用activity还是ListFragment都没有关系你能打印logcat或者用你的错误通知我吗?
【解决方案5】:

使用此代码

 public class LocationUpdateService extends Service {


        private LocationManager _locationManager;
        private boolean _gpsEnabled,_networkEnabled;
        @Override 
        public IBinder onBind(Intent arg0) {
            // TODO Auto-generated method stub
            return null;
        }



        @Override
        public void onCreate() {
            // TODO Auto-generated method stub
            super.onCreate();
            _locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            _gpsEnabled = _locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            _networkEnabled = _locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        }

        public void onStart(Intent intent, int startId) {

            Log.e("onStart","onStart");

            if( _gpsEnabled ) {
                _locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                        1000, 0, locationListener);
            } else if ( _networkEnabled ){
                _locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                        1000, 0, locationListener);
            }

        };




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

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onLocationChanged(final Location location) {
            final Location currentLocation = location;

            Log.e("onLocationChanged", " " + currentLocation);
            _locationManager.removeUpdates(locationListener);

            Toast.makeText(LocationUpdateService_2.this, "Location lat "+currentLocation.getLatitude()+ " long "+currentLocation.getLongitude() , Toast.LENGTH_LONG).show();

    }

    };

【讨论】:

    猜你喜欢
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 2016-09-15
    • 2017-05-09
    • 2012-07-08
    • 2015-09-07
    • 2013-01-11
    相关资源
    最近更新 更多