2013-02-22 132 views
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位數字?

+2

在小數點後8位,您會要求精確度爲1毫米左右的公式。你預計哪款GPS設備能夠讓你的當前位置達到最接近的千分之一毫米? (如果你「需要」這個精度,我會建議你的設計被打破。) – 2013-02-22 07:10:22

回答

3

當以十進制度數測量時,您不必在逗號後得到12位數字,這是常見的表示形式。這不是由任何人完成的。

7位數字在毫米範圍內。

12位數字是千分之一毫米。

保留7位數字,也可以表示爲整數。

+0

除此之外,GPS不是那麼準確。超過小數點後第五位的任何內容都只是一個猜測。 – psubsee2003 2013-02-22 12:44:42

+0

@ psubsee2003,是的,正確的。 5位數就足夠了。如果這是存儲要求,則不會使用5位數字保存任何內容。 7位使用4個字節,5位使用4個字節。另外5位數字是一米精度。不要忘記,GPS具有不超過5位數的絕對精確度,但它的相對精度要高得多。如果您只使用5位數字,則在屏幕上繪製座標時,將在該1米柵格上左右跳躍1米(= 5位數字)。在使用7位數字時,您可以獲得平穩的視圖(6位數字) – AlexWien 2013-02-23 00:29:14

2

據美國政府

的實際精度達到用戶依賴於 政府無法控制的因素,包括大氣的影響和接收器 質量。由FAA收集真實世界的數據表明,一些 高質量GPS SPS接收機目前提供優於3米 水平GPS.gov

這種精確度涉及5個小數

0.0001 =11.1米

0.00001 = 1.11 m

因此,對於Android設備來說,4個位置的準確度是合理的。

+0

不,錯誤的是,您已經向我們表明了絕對定位精度的3米精度,而不是相對精度。嘗試導出到谷歌地圖,一個4位數的分辨率的修補程序的軌跡,你會看到,修復將在11米柵格左右跳躍,真是醜陋!在此期間,我建議6位數字。 – AlexWien 2013-03-21 11:16:28

+0

用戶聲明他只能達到4位數字。當然,如果需要映射6位數是 – 2013-03-21 11:44:42

+0

有趣和奇怪,他只能得到4位數。但是,在所有情況下,當您存儲協調文件時,您都不會在文件格式中截斷爲4位數。 (如果您稍後有更多數字並嘗試計算兩個後續座標之間的標題,則由4位數字柵格導致您的標題偏離30度以上)。 – AlexWien 2013-03-21 12:19:58