我有一个应用程序,我必须从纬度和经度中获取用户的当前位置.对于这两个值,我必须得到小数点后 12 位.
I have an application in which I have to get user's current location from latitude and longitude. For both the values, I have to get 12 digits after decimal.
这是用于获取用户位置的 gps 跟踪器类:
This is the gps tracker class for getting the user location:
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 类的服务类:
This is the service class from which I am accessing the GPSTracker class:
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 位数字?
Currently I am getting 4 digits after decimal for both latitude and longitude. What should I do to get 12 digits after latitude and longitude values?
用十进制度量度时,逗号后不必取 12 位,这是常用的表示法.这不是任何人做的.
You do not have to get 12 digits after comma when measuring in decimal degrees, which is the common representation. It is not being done by any one.
7 位在毫米范围内.
12 位是千分之一毫米.
12 digits is a ten thousandth of a millimeter.
保留 7 位数字,也可以表示为整数.
Stay with 7 digits, which can be represented as integer too.
这篇关于获取纬度和经度的小数点后十二位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!