2

我有一个应用程序,我必须从纬度和经度中获取用户的当前位置。对于这两个值,我必须得到小数点后的 12 位数字。

这是用于获取用户位置的 gps 跟踪器类:

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
    private String locationUsing;

    // 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 and GPS is enabled
                Log.d("No GPS & Network", "no network provider and GPS is enabled");
            } 

            else 
            {
                this.canGetLocation = true;
//==================================================================================================================
//First it will try to get Location using GPS if it not going to get GPS 
//then it will get Location using Tower Location of your network provider
//==================================================================================================================

                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) 
                {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS", "Get loc using GPS");
                    if (locationManager != null) 
                    {
                        Log.d("locationManager", "locationManager not null");
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) 
                        {
                            Log.d("location", "location Not null");
                            latitude  = location.getLatitude();
                            longitude = location.getLongitude();
                            setLocationUsing("GPS");
                        }
                    }
                }
                //if GPS is Off then get lat/long using Network
                if (isNetworkEnabled) 
                {                   
                    if (location == null) 
                    {
                        Log.d("Network", "Get loc using Network");
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                        if (locationManager != null) 
                        {
                            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            if (location != null) 
                            {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                                setLocationUsing("Network");
                            }
                        }
                    }
                }

            }

        } 
        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/Network enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will launch 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;
    }

    public String getLocationUsing() {
        return locationUsing;
    }

    void setLocationUsing(String locationUsing) {
        this.locationUsing = locationUsing;
    }
}

这是我从中访问 GPSTracker 类的服务类:

public class MyAlarmService extends Service {

        String device_id;
    // GPSTracker class
       GPSTracker gps;

       String date_time;

       String lat_str;
       String lon_str;

       static String response_str=null;
        static String response_code=null;
@Override
public void onCreate() {
 // TODO Auto-generated method stub
    //Toast.makeText(this, "Service created", Toast.LENGTH_LONG).show();

    //---get a Record---

    }

@Override
public IBinder onBind(Intent intent) {
 // TODO Auto-generated method stub
 //Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
 return null;
}

@Override
public void onDestroy() {
 // TODO Auto-generated method stub
 super.onDestroy();
 //this.stopSelf();
 //Toast.makeText(this, "Service Destroyed.", Toast.LENGTH_LONG).show();
}

@Override
public void onStart(Intent intent, int startId) {
 // TODO Auto-generated method stub
 super.onStart(intent, startId);

 //Toast.makeText(this, "Service Started.", Toast.LENGTH_LONG).show();


//create class object

 gps = new GPSTracker(this);

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



        //double latitude = gps.getLatitude();
        double latitude = gps.getLatitude();
        double longitude =gps.getLongitude();
        String locationUsing = gps.getLocationUsing();

        makeAToast("Latitude: "+latitude+", "+" Longitude: "+longitude);

         final TelephonyManager tm =(TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);

         String deviceid = tm.getDeviceId();




         Date formattedDate = new Date(System.currentTimeMillis());

         SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm a", Locale.US);

         date_time = sdf.format(formattedDate);


         SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
         final String part_id=preferences.getString("Part_Id","");

         final String Tracker = preferences.getString("Tracker_enabled","");

        lat_str=""+latitude;
        lon_str=""+longitude;


        if(haveNetworkConnection())
        {
            if (Tracker.contains("true"))
            {

            Log.i("Tracker value: ", Tracker);  
            sendPostRequest(part_id,deviceid,lat_str,lon_str,date_time);
            }
        }
        else
        {
            //Toast.makeText( getApplicationContext(),"No Internet connection or Wifi available",Toast.LENGTH_LONG).show();
        }
     }
     else
     {
        // GPS or Network is not enabled
        Toast.makeText(getApplicationContext(), "No Network or GPS", Toast.LENGTH_LONG).show();
     }
}

@Override
public boolean onUnbind(Intent intent) {
 // TODO Auto-generated method stub
 // Toast.makeText(this, "Service binded", Toast.LENGTH_LONG).show();
 return super.onUnbind(intent);
}

//=======================================================================================================
//check packet data and wifi
//=======================================================================================================
private boolean haveNetworkConnection() 
{
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) 
    {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                haveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                haveConnectedMobile = true;
    }
    return haveConnectedWifi || haveConnectedMobile;
}
//=======================================================================================================
    //checking packet data and wifi END
    //=======================================================================================================


//sending async post request---------------------------------------------------------------------------------------
    private void sendPostRequest(final String part_id, final String device_id,final String lat,final String lon, final String status_datetime) {

        class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{

            @Override
            protected String doInBackground(String... params) {

                String result = "";
                HttpClient hc = new DefaultHttpClient();
                String message;

                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MyAlarmService.this);
                  final String url_first = preferences.getString("URLFirstPart","");


                HttpPost p = new HttpPost(url_first+"SetTrakerLatLon");
                JSONObject object = new JSONObject();

                try {
                    object.put("PartId",part_id);
                    object.put("DeviceId",device_id);
                    object.put("Lat", lat);
                    object.put("Lon", lon);
                    object.put("DateTime", status_datetime);

                } catch (Exception ex) {

                }

                try {
                message = object.toString();

                p.setEntity(new StringEntity(message, "UTF8"));
                p.setHeader("Content-type", "application/json");
                    HttpResponse resp = hc.execute(p);

                    response_code=""+ resp.getStatusLine().getStatusCode();

                        InputStream inputStream = resp.getEntity().getContent();
                        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                        StringBuilder stringBuilder = new StringBuilder();
                        String bufferedStrChunk = null;

                        while((bufferedStrChunk = bufferedReader.readLine()) != null){
                            stringBuilder.append(bufferedStrChunk);
                        }

                        response_str= stringBuilder.toString();

                        Log.i("Tracker Response: ",response_str);





                    if (resp != null) {
                        if (resp.getStatusLine().getStatusCode() == 204)
                            result = "true";


                    }


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


                }

                return result;

            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);




            }           
        }

        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute();     
    }


    //-----------------------------------------------------------------------------------------------



//public void sendDataToServer(String time, String date) {
public void sendDataToServer(String deviceid,String date_time,String latitude,String longitude) {
    // TODO Auto-generated method stub


    try {
        HttpClient client = new DefaultHttpClient();  
        String postURL = "http://192.168.1.60/trackme/trackservice.svc/SetLatLon?";
        HttpPost post = new HttpPost(postURL); 
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("mobileId", deviceid));
            params.add(new BasicNameValuePair("lat", latitude));
            params.add(new BasicNameValuePair("lon", longitude));
            params.add(new BasicNameValuePair("udate", date_time));
            UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
            post.setEntity(ent);
            Log.i("URL: ",EntityUtils.toString(ent));
            HttpResponse responsePOST = client.execute(post);  
            HttpEntity resEntity = responsePOST.getEntity();  
            if (resEntity != null) {    
                Log.i("RESPONSE",EntityUtils.toString(resEntity));
            }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private StringBuilder inputStreamToString(InputStream is) {
String line="";
StringBuilder total=new StringBuilder();
BufferedReader buf=new BufferedReader(new InputStreamReader(is));
try {
    while ((line=buf.readLine())!=null) {
        total.append(line); 
    }
} catch (Exception e) {
    // TODO: handle exception
    makeAToast("Cannot connect to server from your device");
}
return total;
}

//to display a toast in case of message
    public void makeAToast(String str) {
        //yet to implement
        Toast toast = Toast.makeText(this,str, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }


}

目前,我的纬度和经度都得到小数点后 4 位数字。我应该怎么做才能在纬度和经度值之后获得 12 位数字?

4

2 回答 2

4

用十进制度测量时,您不必在逗号后面加上 12 位数字,这是常见的表示。它不是由任何人完成的。

7 位数字在毫米范围内。

12 位是千分之一毫米。

保留 7 位数字,也可以表示为整数。

于 2013-02-22T10:41:44.197 回答
2

根据美国政府

用户获得的实际精度取决于政府无法控制的因素,包括大气效应和接收器质量。美国联邦航空局收集的真实数据显示,一些高质量的 GPS SPS 接收器目前提供优于 3 米的水平GPS.gov

此精度与小数点后 5 位有关

0.0001 = 11.1 米

0.00001 = 1.11 米

因此,对于安卓设备来说,4 位的准确度是合理的。

于 2013-02-22T10:53:40.157 回答