android如何实现LBS定位实例代码分析

你猜 阅读:143 2021-04-01 10:28:06 评论:0

第一步:搭建LBS定位服务,如图所示:

注释说明:locSDK.jar包和liblocSDK3.so是百度开发中心提供的(LBS)服务。自己去下载试试吧。

 

废话不多说,直接上代码:

public class WelcomeActivitys extends Activity {
 // 相关组件获取
 private TextView user;
 private TextView time;
 private TextView xiqi;
 public TextView address;
 private GridView gridview;

 // 百度地图LBS服务工具类
 private LocationClient mLocationClient;
 private MyLocationListener locationlistener;
 // 用户的当前位置
 private double x;
 private double y;

 // 主线程
 Handler handler = new Handler() {
  @Override
  public void handleMessage(Message msg) {
   // TODO Auto-generated method stub
   switch (msg.what) {
   // 解析用户的当前位置信息
   case 0:
    Bundle bundle = msg.getData();
    String a = String.valueOf(bundle.getDouble("x"));
    String b = String.valueOf(bundle.getDouble("y"));

    // 解析用户的当前位置
    String add = AddressUtil.GetAddr(a, b);
    address.setText("用户当前位置:" + add);

    break;

   }

  }

 };

 @Override
 public void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  // 全屏显示相关代码
  this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
  this.requestWindowFeature(Window.FEATURE_NO_TITLE);
  setContentView(R.layout.activity_welcome);
  // 相关方法调用
  init();
  user.setText("欢迎你: 周先生");
  DateUtil.settime(time);
  DateUtil.setdate(xiqi);
  setimage();
  // 百度地图定位(LBS)
  mLocationClient = new LocationClient(this);
  locationlistener = new MyLocationListener(handler);
  mLocationClient.registerLocationListener(locationlistener);
  mLocationClient.start();
  if (mLocationClient != null && mLocationClient.isStarted()) {
   setLocationOption();
   mLocationClient.requestLocation();
  }
 }

 // 组件实例化相关方法
 public void init() {
  user = (TextView) findViewById(R.id.user);
  time = (TextView) findViewById(R.id.time);
  xiqi = (TextView) findViewById(R.id.xiqi);
  address = (TextView) findViewById(R.id.address);
  // gridview组件实例化
  gridview = (GridView) findViewById(R.id.gridView);
 }

 // gridview组件设置图片和相关文字
 public void setimage() {
  // gridView相关字符串资源和图片资源
  String[] names = new String[] { "e掌控功能一", "e掌控功能二", "e掌控功能三", "e掌控功能四",
    "e掌控功能五", "e掌控功能六" };
  int[] images = new int[] { R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher, R.drawable.ic_launcher,
    R.drawable.ic_launcher };

  // gridView相关资源存储
  List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
  for (int i = 0; i < names.length; i++) {
   Map<String, Object> listItem = new HashMap<String, Object>();
   listItem.put("images", images[i]);
   listItem.put("names", names[i]);
   listItems.add(listItem);
  }

  // 创建资源适配器
  SimpleAdapter adapter = new SimpleAdapter(WelcomeActivitys.this,
    listItems, R.layout.gridview_item, new String[] { "images",
      "names" }, new int[] { R.id.ItemImage, R.id.ItemText });
  gridview.setAdapter(adapter);

  // 为gridView创建监听器
  gridview.setOnItemClickListener(new OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> adapter, View view,
     int position, long arg3) {
    switch (position) {
    case 0:
     // 跳转到相关的功能界面0
     Toast.makeText(WelcomeActivitys.this, "跳转到功能界面0",
       Toast.LENGTH_LONG).show();
     break;
    case 1:
     // 跳转到相关的功能界面1
     Toast.makeText(WelcomeActivitys.this, "跳转到功能界面1",
       Toast.LENGTH_LONG).show();
     break;
    case 2:
     // 跳转到相关的功能界面2
     Toast.makeText(WelcomeActivitys.this, "跳转到功能界面2",
       Toast.LENGTH_LONG).show();
     break;
    case 3:
     // 跳转到相关的功能界面3
     Toast.makeText(WelcomeActivitys.this, "跳转到功能界面3",
       Toast.LENGTH_LONG).show();
     break;
    case 4:
     // 跳转到相关的功能界面4
     Toast.makeText(WelcomeActivitys.this, "跳转到功能界面4",
       Toast.LENGTH_LONG).show();
     break;
    case 5:
     // 跳转到相关的功能界面5
     Toast.makeText(WelcomeActivitys.this, "跳转到功能界面5",
       Toast.LENGTH_LONG).show();
     break;
    }
   }

  });

 }

 // 实时位置的显示的问题(LBS)
 public class MyLocationListener implements BDLocationListener {
  private Handler handle;

  public MyLocationListener(Handler handle) {
   super();
   this.handle = handle;
  }

  @Override
  public void onReceiveLocation(BDLocation location) {
   // TODO Auto-generated method stub
   x = location.getLatitude();
   y = location.getLongitude();

   Message message = new Message();
   Bundle bundle = new Bundle();
   bundle.putDouble("x", x);
   bundle.putDouble("y", y);
   message.setData(bundle);
   message.what = 0;
   handle.sendMessage(message);
  }

  @Override
  public void onReceivePoi(BDLocation arg0) {
   // TODO Auto-generated method stub
  }
 }

 // 查询条件显示
 private void setLocationOption() {
  LocationClientOption option = new LocationClientOption();
  option.setOpenGps(true);
  option.setAddrType("all");// 返回的定位结果包含地址信息
  option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
  option.setScanSpan(5000);// 设置发起定位请求的间隔时间为5000ms
  option.disableCache(true);// 禁止启用缓存定位
  option.setPoiNumber(5); // 最多返回POI个数
  option.setPoiDistance(1000); // poi查询距离
  option.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息
  mLocationClient.setLocOption(option);
 }

}

 

第二步:地理位置信息的解析(工具栏)

public class AddressUtil {
 public static String GetAddr(String latitude, String longitude) {
    List list=new ArrayList();
    String addr = "";
    // 也可以是http://maps.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s,不过解析出来的是英文地址
    // 密钥可以随便写一个key=abc
    // output=csv,也可以是xml或json,不过使用csv返回的数据最简洁方便解析
//    String url = String.format(
//      "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&language=zh-cn&latlng=%s,%s",
//      latitude, longitude);
    String url = String.format("http://apis.mapabc.com/rgeocode/simple?sid=7002&region="+longitude+","+latitude+"&range=1000&resType=json&rid=123&key=f03346eb3a99be025979045e8fa1a281c5159611ba5cd95248561cd8efb696214e6fdfa72527114d");
    URL myURL = null;
    URLConnection httpsConn = null;
    JSONObject json = null;
    try {
     myURL = new URL(url);
    } catch (MalformedURLException e) {
     e.printStackTrace();
     return null;
    }
    try {
     httpsConn = (URLConnection) myURL.openConnection();
     if (httpsConn != null) {
      InputStreamReader insr = new InputStreamReader(
        httpsConn.getInputStream(), "gbk");
      BufferedReader br = new BufferedReader(insr);
      String result="";
      String data;
      while ((data = br.readLine()) != null) {
       result+=data;
      }
   
      result=result.substring(result.indexOf("{"), result.length());
      json=new JSONObject(result);
      int i=result.indexOf("posdes");
      if(i>-1){
       String posdes=json.getString("posdes");
       String[] address=posdes.toString().split(";");
       for(String a:address){
        if(a!=null){
         list.add(a);
        }
       }
      }
      if(list.size()<2&&list.size()>0){
       addr="";
       addr+=(String)list.get(0)+"附近";
      }
      if(list.size()==2){
       addr="";
       System.out.println("list=2--------------------");
       String array=(String)list.get(1);
       String[] arrays=array.split(",");
       List alist=new ArrayList();
       for(String a:arrays){
        if(a!=null){
         alist.add(a);
        }
       }
       
       addr+=(String)list.get(0)+(String)alist.get(0);
       if(alist.size()>1){
        addr+=","+(String)alist.get(1);
       }
       addr+="附近";
      }
      if(list.size()>2){
       addr="";
       System.out.println("list>2--------------------");
       String array=(String)list.get(2);
       String[] arrays=array.split(",");
       List alist=new ArrayList();
       for(String a:arrays){
        if(a!=null){
         alist.add(a);
        }
       }
       String temp=(String)list.get(1);
       addr+=(String)list.get(0)+temp+(String)alist.get(0);
       if(alist.size()>1){
        addr+=","+(String)alist.get(1);
       }
       addr+="附近";
      }
      System.out.println(addr+"\t------------");
      insr.close();
     }
    } catch (IOException e) {
     e.printStackTrace();
     System.out.println(e.getMessage());  
     return null;
    } catch (JSONException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
    if("附近附近".equals(addr)){
     addr="";
    }
    return addr;
   }

}

 

 

 

声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

发表评论
搜索
排行榜
关注我们

可以免费观看全网VIP电影的公众号