当前位置: 移动技术网 > IT编程>移动开发>Android > Android百度地图定位后获取周边位置的实现代码

Android百度地图定位后获取周边位置的实现代码

2019年07月24日  | 移动技术网IT编程  | 我要评论

m1185,俏天使赖上霸王龙,姚毅诚

本文实例讲解android百度地图定位后获取周边位置的实现代码,分享给大家供大家参考,具体内容如下

效果图:

具体代码:

1.布局文件

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
  <relativelayout
      android:layout_width="match_parent"
      android:layout_height="@dimen/height_top_bar"
      android:background="@color/common_top_bar_dark"
      android:gravity="center_vertical">

    <button
        android:id="@+id/btn_location_back"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:drawableleft="@drawable/back"
        android:text="@string/top_back"
        style="@style/btn_title_bar"
        android:layout_alignparentleft="true"
        android:onclick="back"
        />

    <textview
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerinparent="true"
        android:text="@string/location_message"
        style="@style/txt_titlebar_message"/>


    <button
        android:id="@+id/btn_location_ok"
        android:layout_width="52dp"
        android:layout_height="match_parent"
        android:layout_alignparentright="true"
        android:background="@drawable/common_tab_bg"
        android:text="@string/txt_queding"
        style="@style/btn_title_bar"/>

  </relativelayout>
  <com.baidu.mapapi.map.mapview
      android:layout_weight="2"
      android:id="@+id/mapview_location"
      android:layout_width="fill_parent"
      android:layout_height="match_parent"
      android:clickable="true" />

  <listview
      android:layout_weight="3"
      android:id="@+id/lv_location_nearby"
      android:layout_width="match_parent"
      android:layout_height="match_parent"/>

</linearlayout>


布局文件就是上面是一个百度地图的mapview,下面是一个显示周边位置的listview,很简单。

1、自动定位

我们先看一下根据自己的地理位置实现定位
1.首先初始化要用到的组件

 /**
   * 初始化组件
   */
  private void initview() {
    btnlocationback = (button) findviewbyid(r.id.btn_location_back);
    btnlocationback.setonclicklistener(this);
    btnlocationok = (button) findviewbyid(r.id.btn_location_ok);
    btnlocationok.setonclicklistener(this);
    mapviewlocation = (mapview) findviewbyid(r.id.mapview_location);
    lvlocnear = (listview) findviewbyid(r.id.lv_location_nearby);
    nearlist = new arraylist<poiinfo>();
    adapter = new locnearaddressadapter(context, nearlist, isselected);
    lvlocnear.setadapter(adapter);
  }

2.初始化locationclient类,该类需要在主线程中声明

public locationclient mlocationclient = null;
public bdlocationlistener mylistener = new mylocationlistener();

public void oncreate() {
  mlocationclient = new locationclient(getapplicationcontext());   //声明locationclient类
  mlocationclient.registerlocationlistener( mylistener );  //注册监听函数
}

3.配置定位sdk参数
设置定位参数包括:定位模式(高精度定位模式,低功耗定位模式和仅用设备定位模式),返回坐标类型,是否打开gps,是否返回地址信息、位置语义化信息、poi信息等等。
locationclientoption类,该类用来设置定位sdk的定位方式

private void initlocation(){
    locationclientoption option = new locationclientoption();
    option.setlocationmode(locationmode.hight_accuracy
);//可选,默认高精度,设置定位模式,高精度,低功耗,仅设备
    option.setcoortype("bd09ll");//可选,默认gcj02,设置返回的定位结果坐标系
    int span=1000;
    option.setscanspan(span);//可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的
    option.setisneedaddress(true);//可选,设置是否需要地址信息,默认不需要
    option.setopengps(true);//可选,默认false,设置是否使用gps
    option.setlocationnotify(true);//可选,默认false,设置是否当gps有效时按照1s1次频率输出gps结果
    option.setisneedlocationdescribe(true);//可选,默认false,设置是否需要位置语义化结果,可以在bdlocation.getlocationdescribe里得到,结果类似于“在北京天安门附近”
    option.setisneedlocationpoilist(true);//可选,默认false,设置是否需要poi结果,可以在bdlocation.getpoilist里得到
option.setignorekillprocess(false);//可选,默认false,定位sdk内部是一个service,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认杀死
    option.setignorecacheexception(false);//可选,默认false,设置是否收集crash信息,默认收集
option.setenablesimulategps(false);//可选,默认false,设置是否需要过滤gps仿真结果,默认需要
    mlocationclient.setlocoption(option);
  }

4.实现bdlocationlistener接口

 /**
   * 监听函数,有新位置的时候,格式化成字符串,输出到屏幕中
   */
  public class mylocationlistenner implements bdlocationlistener {
    @override
    public void onreceivelocation(bdlocation location) {
      if (location == null) {
        return;
      }
      log.d("map", "on location change received:" + location);
      log.d("map", "addr:" + location.getaddrstr());
      if (progressdialog != null) {
        progressdialog.dismiss();
      }

      if (lastlocation != null) {
        if (lastlocation.getlatitude() == location.getlatitude() && lastlocation.getlongitude() == location.getlongitude()) {
          log.d("map", "same location, skip refresh");
          // mmapview.refresh(); //need this refresh?
          return;
        }
      }
      lastlocation = location;
      mbaidumap.clear();
      mcurrentlantitude = lastlocation.getlatitude();
      mcurrentlongitude = lastlocation.getlongitude();
      log.e(">>>>>>>", mcurrentlantitude + "," + mcurrentlongitude);
      latlng lla = new latlng(lastlocation.getlatitude(), lastlocation.getlongitude());
      coordinateconverter converter = new coordinateconverter();
      converter.coord(lla);
      converter.from(coordinateconverter.coordtype.common);
      latlng convertlatlng = converter.convert();
      overlayoptions ooa = new markeroptions().position(convertlatlng).icon(bitmapdescriptorfactory
          .fromresource(r.drawable.icon_marka))
          .zindex(4).draggable(true);
      mcurrentmarker = (marker) mbaidumap.addoverlay(ooa);
      mapstatusupdate u = mapstatusupdatefactory.newlatlngzoom(convertlatlng, 16.0f);
      mbaidumap.animatemapstatus(u);
      new thread(new runnable() {
        @override
        public void run() {
          searchneayby();
        }
      }).start();
    }

    public void onreceivepoi(bdlocation poilocation) {
      if (poilocation == null) {
        return;
      }
    }
  }

这里接受到的bdlocation中包含好多参数,相信总有一个对你有用的。

2、根据经纬度定位

这种方法不需要自动定位,就是根据经纬度来显示地图上的位置

 /*
  * 显示经纬度的位置
  * */
  private void showmap(double latitude, double longtitude, string address) {
//    sendbutton.setvisibility(view.gone);
    latlng lla = new latlng(latitude, longtitude);
    coordinateconverter converter = new coordinateconverter();
    converter.coord(lla);
    converter.from(coordinateconverter.coordtype.common);
    latlng convertlatlng = converter.convert();
    overlayoptions ooa = new markeroptions().position(convertlatlng).icon(bitmapdescriptorfactory.fromresource(r.drawable.icon_marka))
        .zindex(4).draggable(true);
    markera = (marker) (mbaidumap.addoverlay(ooa));
    u = mapstatusupdatefactory.newlatlngzoom(convertlatlng, 16.0f);
    mbaidumap.animatemapstatus(u);
    new thread(new runnable() {
      @override
      public void run() {
        searchneayby();
      }
    }).start();
  }

3、获取周边地理位置

最后看一下怎么获取周边的地理位置,这里需要用到sdk中的一个类poinearbysearchoption,我们可以看一下类参考:

  • poinearbysearchoption keyword(java.lang.string key)
  • 检索关键字
  • poinearbysearchoption location(latlng location)
  • 检索位置
  • poinearbysearchoption pagecapacity(int pagecapacity)
  • 设置每页容量,默认为每页10条
  • poinearbysearchoption pagenum(int pagenum)
  • 分页编号
  • poinearbysearchoption radius(int radius)
  • 设置检索的半径范围
  • poinearbysearchoption sorttype(poisorttype sorttype)
  • 搜索结果排序规则,可选,默认

这里是它的一些方法,我们可以看到我们只需要设置一下关键字、周边位置半径、检索位置、排序规则、分页号、每页数量等。然后我们实现ongetpoisearchresultlistener这个接口,获取周边地理位置结果。

/**
   * 搜索周边地理位置
   */
  private void searchneayby() {
    poinearbysearchoption option = new poinearbysearchoption();
    option.keyword("写字楼");
    option.sorttype(poisorttype.distance_from_near_to_far);
    option.location(new latlng(mcurrentlantitude, mcurrentlongitude));
    if (radius != 0) {
      option.radius(radius);
    } else {
      option.radius(1000);
    }

    option.pagecapacity(20);
    mpoisearch.searchnearby(option);

  }

/*
* 接受周边地理位置结果
* @param poiresult
*/

  @override
  public void ongetpoiresult(poiresult poiresult) {
    if (poiresult != null) {
      if (poiresult.getallpoi()!=null&&poiresult.getallpoi().size()>0){
        nearlist.addall(poiresult.getallpoi());
        if (nearlist != null && nearlist.size() > 0) {
          for (int i = 0; i < nearlist.size(); i++) {
            isselected.put(i, false);
          }
        }
        message msg = new message();
        msg.what = 0;
        handler.sendmessage(msg);
      }

    }
  }

获取完数据之后更新适配器显示周边位置就ok了,最后再实现一个小小的功能,就是点击列表中的每个位置,显示位置的小图标根据位置的改变而改变

 /**
     * 周边地理位置列表点击事件
     */
    lvlocnear.setonitemclicklistener(new adapterview.onitemclicklistener() {
      @override
      public void onitemclick(adapterview<?> adapterview, view view, int i, long l) {
        adapter.setselected(i);
        adapter.notifydatasetchanged();
        poiinfo ad = (poiinfo) adapter.getitem(i);
        u = mapstatusupdatefactory.newlatlng(ad.location);
        mbaidumap.animatemapstatus(u);
        if (!isloc) {
          mcurrentmarker.setposition(ad.location);
        } else {
          markera.setposition(ad.location);
        }
      }
    });

好了,很简单有用的一个小功能,会给用户带来很好的体验效果。

希望大家会喜欢这篇文章。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网