Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android中使用百度定位sdk實時的計算移動距離

android中使用百度定位sdk實時的計算移動距離

編輯:關於Android編程

前段時間因為項目需求,通過百度定位adk寫了一個實時更新距離的程序(類似大家坐的士時,車上的裡程表),遇到很多技術點,總結了一下發表出來和大家相互學習。直接要求定位具體的位置應該是不難的,只需要引入百度定位adk,並配置相關參數就可以完成,顯示百度地圖也類似,但是如果需要不斷的實時顯示移動距離,GPS定位從一個點,到第二個點,從第二個點,到第三個點,從第三個點......,移動距離是多少呢?不得不說,要實現這種需求的確存在一定的難度。

目標:使用百度定位sdk開發實時移動距離計算功能,根據經緯度的定位,計算行駛公裡數並實時刷新界面顯示。
大家都知道定位有三種方式:GPS 、Wifi 、 基站 .
誤差方面的話,使用GPS誤差在10左右,Wifi則在20 - 300左右 ,而使用基站則誤差在100 - 300左右的樣子,因為在室內GPS是定位不到的,必須在室外,
而我們項目的需求正好需要使用GPS定位,所以我們這裡設置GPS優先。車,不可能在室內跑吧。


使用技術點:
1.百度定位sdk
2.sqlite數據庫(用於保存經緯度和實時更新的距離)
3.通過經緯度計算距離的算法方式
4.TimerTask 、Handler


大概思路:
1)創建項目,上傳應用到百度定位sdk獲得應用對應key,並配置定位服務成功。
2)將配置的定位代碼塊放入service中,使程序在後台不斷更新經緯度
3)為應用創建數據庫和相應的數據表,編寫 增刪改查 業務邏輯方法
4)編寫界面,通過點擊按鈕控制是否開始計算距離,並引用數據庫,初始化表數據,實時刷新界面
5)在service的定位代碼塊中計算距離,並將距離和經緯度實時的保存在數據庫(注:只要經緯度發生改變,計算出來的距離就要進行保存)

6)界面的刷新顯示

文章後附源碼下載鏈接

以下是MainActivity中的代碼,通過注釋可以理解思路流程.

 

[java]  
  1. package app.ui.activity;
  2. import java.util.Timer;
  3. import java.util.TimerTask;
  4. import android.content.Intent;
  5. import android.os.Bundle;
  6. import android.os.Handler;
  7. import android.os.Message;
  8. import android.view.View;
  9. import android.view.WindowManager;
  10. import android.widget.Button;
  11. import android.widget.TextView;
  12. import android.widget.Toast;
  13. import app.db.DistanceInfoDao;
  14. import app.model.DistanceInfo;
  15. import app.service.LocationService;
  16. import app.ui.ConfirmDialog;
  17. import app.ui.MyApplication;
  18. import app.ui.R;
  19. import app.utils.ConstantValues;
  20. import app.utils.LogUtil;
  21. import app.utils.Utils;
  22.  
  23. public class MainActivity extends Activity {
  24.  
  25. private TextView mTvDistance; //控件
  26. private Button mButton;
  27. private TextView mLng_lat;
  28. private boolean isStart = true; //是否開始計算移動距離
  29.  
  30. private DistanceInfoDao mDistanceInfoDao; //數據庫
  31. private volatile boolean isRefreshUI = true; //是否暫停刷新UI的標識
  32. private static final int REFRESH_TIME = 5000; //5秒刷新一次
  33.  
  34. private Handler refreshHandler = new Handler(){ //刷新界面的Handler
  35. public void handleMessage(Message msg) {
  36. switch (msg.what) {
  37. case ConstantValues.REFRESH_UI:
  38. if (isRefreshUI) {
  39. LogUtil.info(DistanceComputeActivity.class, refresh ui);
  40. DistanceInfo mDistanceInfo = mDistanceInfoDao.getById(MyApplication.orderDealInfoId);
  41. LogUtil.info(DistanceComputeActivity.class, 界面刷新---> +mDistanceInfo);
  42. if (mDistanceInfo != null) {
  43. mTvDistance.setText(String.valueOf(Utils.getValueWith2Suffix(mDistanceInfo.getDistance())));
  44. mLng_lat.setText(經:+mDistanceInfo.getLongitude()+ 緯:+mDistanceInfo.getLatitude());
  45. mTvDistance.invalidate();
  46. mLng_lat.invalidate();
  47. }
  48. }
  49. break;
  50. }
  51. super.handleMessage(msg);
  52. }
  53. };
  54.  
  55. //定時器,每5秒刷新一次UI
  56. private Timer refreshTimer = new Timer(true);
  57. private TimerTask refreshTask = new TimerTask() {
  58. @Override
  59. public void run() {
  60. if (isRefreshUI) {
  61. Message msg = refreshHandler.obtainMessage();
  62. msg.what = ConstantValues.REFRESH_UI;
  63. refreshHandler.sendMessage(msg);
  64. }
  65. }
  66. };
  67.  
  68. @Override
  69. protected void onCreate(Bundle savedInstanceState) {
  70. super.onCreate(savedInstanceState);
  71. getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
  72. WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); //保持屏幕常亮
  73. setContentView(R.layout.activity_expensecompute);
  74.  
  75. startService(new Intent(this,LocationService.class)); //啟動定位服務
  76. Toast.makeText(this,已啟動定位服務..., 1).show();
  77. init(); //初始化相應控件
  78. }
  79.  
  80. private void init(){
  81. mTvDistance = (TextView) findViewById(R.id.tv_drive_distance);
  82. mDistanceInfoDao = new DistanceInfoDao(this);
  83. refreshTimer.schedule(refreshTask, 0, REFRESH_TIME);
  84. mButton = (Button)findViewById(R.id.btn_start_drive);
  85. mLng_lat = (TextView)findViewById(R.id.longitude_Latitude);
  86. }
  87.  
  88.  
  89. @Override
  90. public void onClick(View v) {
  91. super.onClick(v);
  92. switch (v.getId()) {
  93. case R.id.btn_start_drive: //計算距離按鈕
  94. if(isStart)
  95. {
  96. mButton.setBackgroundResource(R.drawable.btn_selected);
  97. mButton.setText(結束計算);
  98. isStart = false;
  99. DistanceInfo mDistanceInfo = new DistanceInfo();
  100. mDistanceInfo.setDistance(0f); //距離初始值
  101. mDistanceInfo.setLongitude(MyApplication.lng); //經度初始值
  102. mDistanceInfo.setLatitude(MyApplication.lat); //緯度初始值
  103. int id = mDistanceInfoDao.insertAndGet(mDistanceInfo); //將值插入數據庫,並獲得數據庫中最大的id
  104. if (id != -1) {
  105. MyApplication.orderDealInfoId = id; //將id賦值到程序全局變量中(注:該id來決定是否計算移動距離)
  106. Toast.makeText(this,已開始計算..., 0).show();
  107. }else{
  108. Toast.makeText(this,id is -1,無法執行距離計算代碼塊, 0).show();
  109. }
  110. }else{
  111. //自定義提示框
  112. ConfirmDialog dialog = new ConfirmDialog(this, R.style.dialogNoFrame){
  113. @Override
  114. public void setDialogContent(TextView content) {
  115. content.setVisibility(View.GONE);
  116. }
  117. @Override
  118. public void setDialogTitle(TextView title) {
  119. title.setText(確認結束計算距離 ?);
  120. }
  121. @Override
  122. public void startMission() {
  123. mButton.setBackgroundResource(R.drawable.btn_noselect);
  124. mButton.setText(開始計算);
  125. isStart = true;
  126. isRefreshUI = false; //停止界面刷新
  127. if (refreshTimer != null) {
  128. refreshTimer.cancel();
  129. refreshTimer = null;
  130. }
  131. mDistanceInfoDao.delete(MyApplication.orderDealInfoId); //刪除id對應記錄
  132. MyApplication.orderDealInfoId = -1; //停止定位計算
  133. Toast.makeText(DistanceComputeActivity.this,已停止計算..., 0).show();
  134. }
  135. };
  136. dialog.show();
  137. }
  138. break;
  139. }
  140. }
  141. }

     

    以下是LocationService中的代碼,即配置的百度定位sdk代碼塊,放在繼承了service的類中 LocationService.java (方便程序在後台實時更新經緯度)

     

    [java] 
    1. package app.service;
    2. import java.util.concurrent.Callable;
    3. import java.util.concurrent.ExecutorService;
    4. import java.util.concurrent.Executors;
    5. import android.app.Service;
    6. import android.content.Intent;
    7. import android.os.IBinder;
    8. import app.db.DistanceInfoDao;
    9. import app.model.GpsLocation;
    10. import app.model.DistanceInfo;
    11. import app.ui.MyApplication;
    12. import app.utils.BDLocation2GpsUtil;
    13. import app.utils.FileUtils;
    14. import app.utils.LogUtil;
    15. import com.baidu.location.BDLocation;
    16. import com.baidu.location.BDLocationListener;
    17. import com.baidu.location.LocationClient;
    18. import com.baidu.location.LocationClientOption;
    19. import com.computedistance.DistanceComputeInterface;
    20. import com.computedistance.impl.DistanceComputeImpl;
    21.  
    22. public class LocationService extends Service {
    23.  
    24. public static final String FILE_NAME = log.txt; //日志
    25. LocationClient mLocClient;
    26. private Object lock = new Object();
    27. private volatile GpsLocation prevGpsLocation = new GpsLocation(); //定位數據
    28. private volatile GpsLocation currentGpsLocation = new GpsLocation();
    29. private MyLocationListenner myListener = new MyLocationListenner();
    30. private volatile int discard = 1; //Volatile修飾的成員變量在每次被線程訪問時,都強迫從共享內存中重讀該成員變量的值。
    31. private DistanceInfoDao mDistanceInfoDao;
    32. private ExecutorService executor = Executors.newSingleThreadExecutor();
    33.  
    34. @Override
    35. public IBinder onBind(Intent intent) {
    36. return null;
    37. }
    38.  
    39. @Override
    40. public void onCreate() {
    41. super.onCreate();
    42. mDistanceInfoDao = new DistanceInfoDao(this); //初始化數據庫
    43. //LogUtil.info(LocationService.class, Thread id ----------->: + Thread.currentThread().getId());
    44. mLocClient = new LocationClient(this);
    45. mLocClient.registerLocationListener(myListener);
    46. //定位參數設置
    47. LocationClientOption option = new LocationClientOption();
    48. option.setCoorType(bd09ll); //返回的定位結果是百度經緯度,默認值gcj02
    49. option.setAddrType(all); //返回的定位結果包含地址信息
    50. option.setScanSpan(5000); //設置發起定位請求的間隔時間為5000ms
    51. option.disableCache(true); //禁止啟用緩存定位
    52. option.setProdName(app.ui.activity);
    53. option.setOpenGps(true);
    54. option.setPriority(LocationClientOption.GpsFirst); //設置GPS優先
    55. mLocClient.setLocOption(option);
    56. mLocClient.start();
    57. mLocClient.requestLocation();
    58.  
    59. }
    60.  
    61. @Override
    62. @Deprecated
    63. public void onStart(Intent intent, int startId) {
    64. super.onStart(intent, startId);
    65. }
    66.  
    67. @Override
    68. public void onDestroy() {
    69. super.onDestroy();
    70. if (null != mLocClient) {
    71. mLocClient.stop();
    72. }
    73. startService(new Intent(this, LocationService.class));
    74. }
    75.  
    76. private class Task implements Callable{
    77. private BDLocation location;
    78. public Task(BDLocation location){
    79. this.location = location;
    80. }
    81.  
    82. /**
    83. * 檢測是否在原地不動
    84. *
    85. * @param distance
    86. * @return
    87. */
    88. private boolean noMove(float distance){
    89. if (distance < 0.01) {
    90. return true;
    91. }
    92. return false;
    93. }
    94.  
    95. /**
    96. * 檢測是否在正確的移動
    97. *
    98. * @param distance
    99. * @return
    100. */
    101. private boolean checkProperMove(float distance){
    102. if(distance <= 0.1 * discard){
    103. return true;
    104. }else{
    105. return false;
    106. }
    107. }
    108.  
    109. /**
    110. * 檢測獲取的數據是否是正常的
    111. *
    112. * @param location
    113. * @return
    114. */
    115. private boolean checkProperLocation(BDLocation location){
    116. if (location != null && location.getLatitude() != 0 && location.getLongitude() != 0){
    117. return true;
    118. }
    119. return false;
    120. }
    121.  
    122. @Override
    123. public String call() throws Exception {
    124. synchronized (lock) {
    125. if (!checkProperLocation(location)){
    126. LogUtil.info(LocationService.class, location data is null);
    127. discard++;
    128. return null;
    129. }
    130.  
    131. if (MyApplication.orderDealInfoId != -1) {
    132. DistanceInfo mDistanceInfo = mDistanceInfoDao.getById(MyApplication.orderDealInfoId); //根據MainActivity中賦值的全局id查詢數據庫的值
    133. if(mDistanceInfo != null) //不為空則說明車已經開始行使,並可以獲得經緯度,計算移動距離
    134. {
    135. LogUtil.info(LocationService.class, 行駛中......);
    136. GpsLocation tempGpsLocation = BDLocation2GpsUtil.convertWithBaiduAPI(location); //位置轉換
    137. if (tempGpsLocation != null) {
    138. currentGpsLocation = tempGpsLocation;
    139. }else{
    140. discard ++;
    141. }
    142. //日志
    143. String logMsg = (plat:---> + prevGpsLocation.lat + plgt:---> + prevGpsLocation.lng +) +
    144. (clat:---> + currentGpsLocation.lat + clgt:---> + currentGpsLocation.lng + );
    145. LogUtil.info(LocationService.class, logMsg);
    146.  
    147. /** 計算距離 */
    148. float distance = 0.0f;
    149. DistanceComputeInterface distanceComputeInterface = DistanceComputeImpl.getInstance(); //計算距離類對象
    150. distance = (float) distanceComputeInterface.getLongDistance(prevGpsLocation.lat,prevGpsLocation.lng,
    151. currentGpsLocation.lat,currentGpsLocation.lng); //移動距離計算
    152. if (!noMove(distance)) { //是否在移動
    153. if (checkProperMove(distance)) { //合理的移動
    154. float drivedDistance = mDistanceInfo.getDistance();
    155. mDistanceInfo.setDistance(distance + drivedDistance); //拿到數據庫原始距離值, 加上當前值
    156. mDistanceInfo.setLongitude(currentGpsLocation.lng); //經度
    157. mDistanceInfo.setLatitude(currentGpsLocation.lat); //緯度
    158.  
    159. //日志記錄
    160. FileUtils.saveToSDCard(FILE_NAME,移動距離--->:+distance+drivedDistance+ +數據庫中保存的距離+mDistanceInfo.getDistance());
    161. mDistanceInfoDao.updateDistance(mDistanceInfo);
    162. discard = 1;
    163. }
    164. }
    165. prevGpsLocation = currentGpsLocation;
    166. }
    167. }
    168. return null;
    169. }
    170. }
    171. }
    172.  
    173. /**
    174. * 定位SDK監聽函數
    175. */
    176. public class MyLocationListenner implements BDLocationListener {
    177. @Override
    178. public void onReceiveLocation(BDLocation location) {
    179. executor.submit(new Task(location));
    180.  
    181. LogUtil.info(LocationService.class, 經度:+location.getLongitude());
    182. LogUtil.info(LocationService.class, 緯度:+location.getLatitude());
    183. //將經緯度保存於全局變量,在MainActivity中點擊按鈕時初始化數據庫字段
    184. if(MyApplication.lng <=0 && MyApplication.lat <= 0)
    185. {
    186. MyApplication.lng = location.getLongitude();
    187. MyApplication.lat = location.getLatitude();
    188. }
    189. }
    190.  
    191. public void onReceivePoi(BDLocation poiLocation) {
    192. if (poiLocation == null){
    193. return ;
    194. }
    195. }
    196. }
    197. } 以下是應用中需要使用的DBOpenHelper數據庫類 DBOpenHelper.java

       

      [java] 
      1. package app.db;
      2. import android.content.Context;
      3. import android.database.sqlite.SQLiteDatabase;
      4. import android.database.sqlite.SQLiteOpenHelper;
      5.  
      6. public class DBOpenHelper extends SQLiteOpenHelper{
      7. private static final int VERSION = 1; //數據庫版本號
      8. private static final String DB_NAME = distance.db; //數據庫名
      9.  
      10. public DBOpenHelper(Context context){ //創建數據庫
      11. super(context, DB_NAME, null, VERSION);
      12. }
      13.  
      14. @Override
      15. public void onCreate(SQLiteDatabase db) { //創建數據表
      16. db.execSQL(CREATE TABLE IF NOT EXISTS milestone(id INTEGER PRIMARY KEY AUTOINCREMENT, distance INTEGER,longitude DOUBLE, latitude DOUBLE ));
      17. }
      18.  
      19. @Override
      20. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //版本號發生改變的時
      21. db.execSQL(drop table milestone);
      22. db.execSQL(CREATE TABLE IF NOT EXISTS milestone(id INTEGER PRIMARY KEY AUTOINCREMENT, distance INTEGER,longitude FLOAT, latitude FLOAT ));
      23. }
      24.  
      25. }

         

        以下是應用中需要使用的數據庫業務邏輯封裝類 DistanceInfoDao.java

         

        [java] 
        1. package app.db;
        2. import android.content.Context;
        3. import android.database.Cursor;
        4. import android.database.sqlite.SQLiteDatabase;
        5. import app.model.DistanceInfo;
        6. import app.utils.LogUtil;
        7.  
        8. public class DistanceInfoDao {
        9. private DBOpenHelper helper;
        10. private SQLiteDatabase db;
        11.  
        12. public DistanceInfoDao(Context context) {
        13. helper = new DBOpenHelper(context);
        14. }
        15.  
        16. public void insert(DistanceInfo mDistanceInfo) {
        17. if (mDistanceInfo == null) {
        18. return;
        19. }
        20. db = helper.getWritableDatabase();
        21. String sql = INSERT INTO milestone(distance,longitude,latitude) VALUES('+ mDistanceInfo.getDistance() + ','+ mDistanceInfo.getLongitude() + ','+ mDistanceInfo.getLatitude() + ');
        22. LogUtil.info(DistanceInfoDao.class, sql);
        23. db.execSQL(sql);
        24. db.close();
        25. }
        26.  
        27. public int getMaxId() {
        28. db = helper.getReadableDatabase();
        29. Cursor cursor = db.rawQuery(SELECT MAX(id) as id from milestone,null);
        30. if (cursor.moveToFirst()) {
        31. return cursor.getInt(cursor.getColumnIndex(id));
        32. }
        33. return -1;
        34. }
        35.  
        36. /**
        37. * 添加數據
        38. * @param orderDealInfo
        39. * @return
        40. */
        41. public synchronized int insertAndGet(DistanceInfo mDistanceInfo) {
        42. int result = -1;
        43. insert(mDistanceInfo);
        44. result = getMaxId();
        45. return result;
        46. }
        47.  
        48. /**
        49. * 根據id獲取
        50. * @param id
        51. * @return
        52. */
        53. public DistanceInfo getById(int id) {
        54. db = helper.getReadableDatabase();
        55. Cursor cursor = db.rawQuery(SELECT * from milestone WHERE id = ?,new String[] { String.valueOf(id) });
        56. DistanceInfo mDistanceInfo = null;
        57. if (cursor.moveToFirst()) {
        58. mDistanceInfo = new DistanceInfo();
        59. mDistanceInfo.setId(cursor.getInt(cursor.getColumnIndex(id)));
        60. mDistanceInfo.setDistance(cursor.getFloat(cursor.getColumnIndex(distance)));
        61. mDistanceInfo.setLongitude(cursor.getFloat(cursor.getColumnIndex(longitude)));
        62. mDistanceInfo.setLatitude(cursor.getFloat(cursor.getColumnIndex(latitude)));
        63. }
        64. cursor.close();
        65. db.close();
        66. return mDistanceInfo;
        67. }
        68.  
        69. /**
        70. * 更新距離
        71. * @param orderDealInfo
        72. */
        73. public void updateDistance(DistanceInfo mDistanceInfo) {
        74. if (mDistanceInfo == null) {
        75. return;
        76. }
        77. db = helper.getWritableDatabase();
        78. String sql = update milestone set distance=+ mDistanceInfo.getDistance() +,longitude=+mDistanceInfo.getLongitude()+,latitude=+mDistanceInfo.getLatitude()+ where id = + mDistanceInfo.getId();
        79. LogUtil.info(DistanceInfoDao.class, sql);
        80. db.execSQL(sql);
        81. db.close();
        82. }
        83. }

           

          以下是需要使用到的實體類 DistanceInfo.java (set數據到對應變量,以實體類作為參數更新數據庫)

           

          [java] 
          1. package app.model;
          2. public class DistanceInfo {
          3. private int id;
          4. private float distance;
          5. private double longitude;
          6. private double latitude;
          7.  
          8. public int getId() {
          9. return id;
          10. }
          11. public void setId(int id) {
          12. this.id = id;
          13. }
          14. public float getDistance() {
          15. return distance;
          16. }
          17. public void setDistance(float distance) {
          18. this.distance = distance;
          19. }
          20. public double getLongitude() {
          21.  
          22. return longitude;
          23. }
          24. public void setLongitude(double longitude) {
          25.  
          26. this.longitude = longitude;
          27. }
          28. public double getLatitude() {
          29.  
          30. return latitude;
          31. }
          32. public void setLatitude(double latitude) {
          33.  
          34. this.latitude = latitude;
          35. }
          36. @Override
          37. public String toString() {
          38.  
          39. return DistanceInfo [id= + id + , distance= + distance
          40. + , longitude= + longitude + , latitude= + latitude + ];
          41. }
          42. }
            保存經緯度信息的類 GpsLocation

             

             

            [java] 
            1. package app.model;
            2. public class GpsLocation {
            3. public double lat;//緯度
            4. public double lng;//經度
            5. } 將從百度定位中獲得的經緯度轉換為精准的GPS數據 BDLocation2GpsUtil.java

               

              [java] view plaincopyprint?在CODE上查看代碼片派生到我的代碼片
              1. package app.utils;
              2. import it.sauronsoftware.base64.Base64;
              3. import java.io.BufferedReader;
              4. import java.io.IOException;
              5. import java.io.InputStreamReader;
              6. import java.net.HttpURLConnection;
              7. import java.net.URL;
              8. import org.json.JSONObject;
              9. import app.model.GpsLocation;
              10. import com.baidu.location.BDLocation;
              11. public class BDLocation2GpsUtil {
              12. static BDLocation tempBDLocation = new BDLocation(); // 臨時變量,百度位置
              13. static GpsLocation tempGPSLocation = new GpsLocation(); // 臨時變量,gps位置
              14. public static enum Method{
              15. origin, correct;
              16. }
              17. private static final Method method = Method.correct;
              18. /**
              19. * 位置轉換
              20. *
              21. * @param lBdLocation 百度位置
              22. * @return GPS位置
              23. */
              24. public static GpsLocation convertWithBaiduAPI(BDLocation lBdLocation) {
              25. switch (method) {
              26. case origin: //原點
              27. GpsLocation location = new GpsLocation();
              28. location.lat = lBdLocation.getLatitude();
              29. location.lng = lBdLocation.getLongitude();
              30. return location;
              31. case correct: //糾偏
              32. //同一個地址不多次轉換
              33. if (tempBDLocation.getLatitude() == lBdLocation.getLatitude() && tempBDLocation.getLongitude() == lBdLocation.getLongitude()) {
              34. return tempGPSLocation;
              35. }
              36. String url = http://api.map.baidu.com/ag/coord/convert?from=0&to=4&
              37. + x= + lBdLocation.getLongitude() + &y=
              38. + lBdLocation.getLatitude();
              39. String result = executeHttpGet(url);
              40. LogUtil.info(BDLocation2GpsUtil.class, result: + result);
              41. if (result != null) {
              42. GpsLocation gpsLocation = new GpsLocation();
              43. try {
              44. JSONObject jsonObj = new JSONObject(result);
              45. String lngString = jsonObj.getString(x);
              46. String latString = jsonObj.getString(y);
              47. // 解碼
              48. double lng = Double.parseDouble(new String(Base64.decode(lngString)));
              49. double lat = Double.parseDouble(new String(Base64.decode(latString)));
              50. // 換算
              51. gpsLocation.lng = 2 * lBdLocation.getLongitude() - lng;
              52. gpsLocation.lat = 2 * lBdLocation.getLatitude() - lat;
              53. tempGPSLocation = gpsLocation;
              54. LogUtil.info(BDLocation2GpsUtil.class, result: + gpsLocation.lat + || + gpsLocation.lng);
              55. } catch (Exception e) {
              56. e.printStackTrace();
              57. return null;
              58. }
              59. tempBDLocation = lBdLocation;
              60. return gpsLocation;
              61. }else{
              62. LogUtil.info(BDLocation2GpsUtil.class, 百度API執行出錯,url is: + url);
              63. return null;
              64. }
              65. }
              66. }
              67. }
                需要聲明相關權限,且項目中所用到的jar有:
                android-support-v4.jar
                commons-codec.jar
                commons-lang3-3.0-beta.jar
                javabase64-1.3.1.jar
                locSDK_3.1.jar

                 

                Android中計算地圖上兩點距離的算法


                項目中目前尚有部分不健全的地方,如:
                1.在行駛等待時間較長後,使用TimerTask 、Handler刷新界面是偶爾會出現卡住的現象,車仍在行駛,
                但是數據不動了,通過改善目前測試近7次未出現此問題。

                2.較快的消耗電量

                源碼下載地址

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved