2

緯度と経度からユーザーの現在の位置を取得する必要があるアプリケーションがあります。両方の値について、10 進数の後に 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

一般的な表現である 10 進度で測定する場合、カンマの後に 12 桁を取得する必要はありません。それは誰によっても行われているわけではありません。

7桁はミリ単位です。

12 桁は 1 万分の 1 ミリです。

整数としても表すことができる7桁にとどまります。

于 2013-02-22T10:41:44.197 に答える
2

米国政府によると

ユーザーが達成する実際の精度は、大気の影響や受信機の品質など、政府の管理外の要因によって異なります。FAA が収集した実世界のデータによると、一部の高品質 GPS SPS 受信機は現在、3 メートル以上の水平GPS.govを提供しています。

この精度は小数点以下 5 桁に関連します。

0.0001 = 11.1m

0.00001 = 1.11m

したがって、Android デバイスでは 4 桁の精度が妥当です。

于 2013-02-22T10:53:40.157 に答える