温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android基于高德地图poi的仿微信获取位置功能实例代码

发布时间:2020-09-13 18:52:53 来源:脚本之家 阅读:375 作者:Emperor_Dandy 栏目:移动开发

 1.打开页面自动定位,同时搜索周边所有poi

Android基于高德地图poi的仿微信获取位置功能实例代码

2.点击搜索按钮,输入关键子,获取关键字搜索结果

Android基于高德地图poi的仿微信获取位置功能实例代码

3。选取listview中的一项即可定位到该位置,或者获取任何消息

Android基于高德地图poi的仿微信获取位置功能实例代码

4.文件类

1、MapActivity

public class MapActivity extends Activity implements PoiSearch.OnPoiSearchListener {
 private MapView mMapView = null;
 private AMap aMap;
 private MyLocationStyle myLocationStyle;
 //poiSearch相关
 private PoiSearch poiSearch;
 private PoiSearch.Query query;
 boolean isPoiSearched = false; //是否进行poi搜索
 //listview
 private ListView ll;
 ArrayList<PoiItem> arrayList;
 MyAdpter adapter;
 MyHandler myHandler;
 //字体
 Typeface tf;
 //搜索栏
 FrameLayout frameLayout;
 ImageView searchIv;
 EditText searchEt;
 TextView title;
 Button btn;
 ImageView success;
 boolean onSearch = false; //是否打开搜索栏
 ImageView back;
 private double mCurrentLat;
 private double mCurrentLng;
 Map<String, String> currentInfo = new HashMap<>();
 int selectIndex = -1;
 ImageView currentSelectItem = null;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_map);
  findAllView();
  setAllViewOnclickLinster();
  //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState),创建地图
  mMapView.onCreate(savedInstanceState);
  initAMap();
 }
 /**
  * 获取view对象,初始化一些对象
  */
 void findAllView() {
  //获取地图控件引用
  mMapView = (MapView) findViewById(R.id.map);
  frameLayout = (FrameLayout) findViewById(R.id.searchLayout);
  searchEt = (EditText) findViewById(R.id.search_input);
  searchIv = (ImageView) findViewById(R.id.search);
  btn = (Button) findViewById(R.id.search_go_btn);
  success = (ImageView) findViewById(R.id.success);
  back = (ImageView) findViewById(R.id.back);
  //初始化listview
  ll = (ListView) findViewById(R.id.ll);
  arrayList = new ArrayList<>();
  adapter = new MyAdpter();
  ll.setAdapter(adapter);
  //设置标题字体
  tf = Typeface.createFromAsset(getAssets(), "font/f1.ttf");
  (title = (TextView) findViewById(R.id.title)).setTypeface(tf);
  myHandler = new MyHandler();
 }
 /**
  * 设置点击事件
  */
 void setAllViewOnclickLinster() {
  //当搜索图标点击时,切换显示效果
  searchIv.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    if (title.getVisibility() == View.VISIBLE) {
     hideTitle();
    } else if (title.getVisibility() == View.GONE) {
     showTitle();
    }
   }
  });
  //点击搜索按钮时,搜索关键字
  btn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    String key = searchEt.getText().toString();
    if (!key.trim().isEmpty()) {
     if (currentSelectItem != null) {
      currentSelectItem.setVisibility(View.INVISIBLE);
     }
     searchPoi(key, 0, currentInfo.get("cityCode"), false);
    }
   }
  });
  //使editText监听回车事件,进行搜索,效果同上
  searchEt.setOnKeyListener(new View.OnKeyListener() {
   @Override
   public boolean onKey(View v, int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
     String key = searchEt.getText().toString();
     if (!key.trim().isEmpty()) {
      if (currentSelectItem != null) {
       currentSelectItem.setVisibility(View.INVISIBLE);
      }
      searchPoi(key, 0, currentInfo.get("cityCode"), false);
     }
     return true;
    }
    return false;
   }
  });
  //返回处理事件
  back.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    if (onSearch) {
     showTitle();
    } else {
     finish();
    }
   }
  });
  //完成事件
  success.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    //点击ok的处理事件
    //获取数据并返回上一个activity即可
   }
  });
  //listview点击事件
  ll.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    Log.e(ProConfig.TAG, i + "");
    PoiItem item = arrayList.get(i);
    Log.e(ProConfig.TAG, item.getLatLonPoint().toString());
    Log.e(ProConfig.TAG, item.toString());
    Log.e(ProConfig.TAG, item.getAdName());
    //在地图上添加一个marker,并将地图中移动至此处
    MarkerOptions mk = new MarkerOptions();
    mk.icon(BitmapDescriptorFactory.defaultMarker());
    mk.title(item.getAdName());
    LatLng ll = new LatLng(item.getLatLonPoint().getLatitude(), item.getLatLonPoint().getLongitude());
    mk.position(ll);
    //清除所有marker等,保留自身
    aMap.clear(true);
    CameraUpdate cu = CameraUpdateFactory.newLatLng(ll);
    aMap.animateCamera(cu);
    aMap.addMarker(mk);
    //存储当前点击位置
    selectIndex = i;
    //存储当前点击view,并修改view和上一个选中view的定位图标
    ImageView iv = (ImageView) view.findViewById(R.id.yes);
    iv.setVisibility(View.VISIBLE);
    if (currentSelectItem != null) {
     currentSelectItem.setVisibility(View.INVISIBLE);
    }
    currentSelectItem = iv;
    if (onSearch) {
     //退出搜索模式,显示地图
     showTitle();
    }
   }
  });
 }
 /**
  * 初始化高德地图
  */
 void initAMap() {
  //初始化地图控制器对象
  if (aMap == null) {
   aMap = mMapView.getMap();
  }
  //地图加载监听器
  aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
   @Override
   public void onMapLoaded() {
    //aMap.setMapType();
    aMap.setMyLocationEnabled(true);
    aMap.animateCamera(CameraUpdateFactory.zoomTo(aMap.getMaxZoomLevel() - 1));
   }
  });
  myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
  myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//连续定位、且将视角移动到地图中心点,定位点依照设备方向旋转,并且会跟随设备移动。(1秒1次定位)如果不设置myLocationType,默认也会执行此种模式。
  myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔,只在连续定位模式下生效,单次定位模式下不会生效。单位为毫秒。
  myLocationStyle.radiusFillColor(0x70f3ff);
  myLocationStyle.strokeColor(0xe3f9fd);
  aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
  aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示,非必需设置。
  aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点,false表示隐藏定位蓝点并不进行定位,默认是false。
  aMap.setMaxZoomLevel(aMap.getMaxZoomLevel());
  //地址监听事件
  aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
   @Override
   public void onMyLocationChange(Location location) {
    if (!isPoiSearched) {
     Log.e(ProConfig.TAG, location.toString());
     Log.e(ProConfig.TAG, location.getProvider());
     Log.e(ProConfig.TAG, location.getLatitude() + ":" + location.getLongitude());
     //存储定位数据
     mCurrentLat = location.getLatitude();
     mCurrentLng = location.getLongitude();
     String[] args = location.toString().split("#");
     for (String arg : args) {
      String[] data = arg.split("=");
      if (data.length >= 2)
       currentInfo.put(data[0], data[1]);
     }
     //搜索poi
     searchPoi("", 0, currentInfo.get("cityCode"), true);
     //latitude=41.652146#longitude=123.427205#province=辽宁省#city=沈阳市#district=浑南区#cityCode=024#adCode=210112#address=辽宁省沈阳市浑南区创新一路靠近东北大学浑南校区#country=中国#road=创新一路#poiName=东北大学浑南校区#street=创新一路#streetNum=193号#aoiName=东北大学浑南校区#poiid=#floor=#errorCode=0#errorInfo=success#locationDetail=24 #csid:1cce9508143d493182a8da7745eb07b3#locationType=5
    }
   }
  });
 }
 @Override
 public boolean onKeyDown(int keyCode, KeyEvent event) {
  //点击返回键时,将浏览器后退
  if (keyCode == KeyEvent.KEYCODE_BACK) {
   if (onSearch) {
    showTitle();
    return true;
   } else
    return super.onKeyDown(keyCode, event);
  }
  return super.onKeyDown(keyCode, event);
 }
 class MyHandler extends Handler {
  @Override
  public void handleMessage(Message msg) {
   super.handleMessage(msg);
   switch (msg.what) {
    case 0x001:
     //加载listview中数据
     adapter.notifyDataSetChanged();
     break;
   }
  }
 }
 /**
  * 自定义adpter
  */
 class MyAdpter extends BaseAdapter {
  @Override
  public int getCount() {
   return arrayList.size();
  }
  @Override
  public Object getItem(int i) {
   return arrayList.get(i);
  }
  @Override
  public long getItemId(int i) {
   return i;
  }
  @Override
  public View getView(int i, View view, ViewGroup viewGroup) {
   //布局加载器
   LayoutInflater inflater = LayoutInflater.from(MapActivity.this);
   //加载location_item布局
   View view1 = inflater.inflate(R.layout.location_item, null);
   //修改文字和字体
   TextView v1 = (TextView) view1.findViewById(R.id.name);
   TextView v2 = (TextView) view1.findViewById(R.id.sub);
   ImageView iv = (ImageView) view1.findViewById(R.id.yes);
   v1.setText(arrayList.get(i).getTitle());
   v1.setTypeface(tf);
   v2.setText(arrayList.get(i).getSnippet());
   v2.setTypeface(tf);
   if (selectIndex == i) {
    iv.setVisibility(View.VISIBLE);
    currentSelectItem = iv;
   } else {
    iv.setVisibility(View.INVISIBLE);
   }
   return view1;
  }
 }
 /**
  * 搜索poi
  *
  * @param key  关键字
  * @param pageNum 页码
  * @param cityCode 城市代码,或者城市名称
  * @param nearby 是否搜索周边
  */
 void searchPoi(String key, int pageNum, String cityCode, boolean nearby) {
  Log.e(ProConfig.TAG, key);
  isPoiSearched = true;
  query = new PoiSearch.Query(key, "", cityCode);
  //keyWord表示搜索字符串,
  //第二个参数表示POI搜索类型,二者选填其一,
  //POI搜索类型共分为以下20种:汽车服务|汽车销售|
  //汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|
  //住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|
  //金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
  //cityCode表示POI搜索区域,可以是城市编码也可以是城市名称,也可以传空字符串,空字符串代表全国在全国范围内进行搜索
  query.setPageSize(50);// 设置每页最多返回多少条poiitem
  query.setPageNum(pageNum);//设置查询页码
  poiSearch = new PoiSearch(this, query);
  poiSearch.setOnPoiSearchListener(this);
  if (nearby)
   poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(mCurrentLat,
     mCurrentLng), 1500));//设置周边搜索的中心点以及半径
  poiSearch.searchPOIAsyn();
 }
 @Override
 public void onPoiSearched(PoiResult poiResult, int i) {
  int index = 0;
  //填充数据,并更新listview
  ArrayList<PoiItem> result = poiResult.getPois();
  if (result.size() > 0) {
   arrayList.clear();
   selectIndex = -1;
   arrayList.addAll(result);
   myHandler.sendEmptyMessage(0x001);
  }
  for (PoiItem item : poiResult.getPois()) {
   Log.e(ProConfig.TAG, item.toString());
   Log.e(ProConfig.TAG, item.getDirection());
   Log.e(ProConfig.TAG, item.getAdName());
  }
 }
 @Override
 public void onPoiItemSearched(PoiItem poiItem, int i) {
 }
 @Override
 protected void onDestroy() {
  super.onDestroy();
  //在activity执行onDestroy时执行mMapView.onDestroy(),销毁地图
  mMapView.onDestroy();
 }
 @Override
 protected void onResume() {
  super.onResume();
  //在activity执行onResume时执行mMapView.onResume (),重新绘制加载地图
  mMapView.onResume();
 }
 @Override
 protected void onPause() {
  super.onPause();
  //在activity执行onPause时执行mMapView.onPause (),暂停地图的绘制
  mMapView.onPause();
 }
 @Override
 protected void onSaveInstanceState(Bundle outState) {
  super.onSaveInstanceState(outState);
  //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState),保存地图当前的状态
  mMapView.onSaveInstanceState(outState);
 }
 /**
  * 显示标题栏,即默认状态
  */
 void showTitle() {
  //显示标题栏
  title.setVisibility(View.VISIBLE);
  success.setVisibility(View.VISIBLE);
  searchEt.setVisibility(View.GONE);
  btn.setVisibility(View.GONE);
  frameLayout.setLayoutParams(
    new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT,
      LinearLayout.LayoutParams.MATCH_PARENT,
      5));
  mMapView.setVisibility(View.VISIBLE);
  onSearch = false;
  closeKeyboard(this);
 }
 /**
  * 隐藏标题栏,即进行搜索
  */
 void hideTitle() {
  //显示搜索框
  title.setVisibility(View.GONE);
  success.setVisibility(View.GONE);
  searchEt.setVisibility(View.VISIBLE);
  btn.setVisibility(View.VISIBLE);
  frameLayout.setLayoutParams(
    new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT,
      LinearLayout.LayoutParams.MATCH_PARENT,
      50));
  mMapView.setVisibility(View.GONE);
  onSearch = true;
 }
 /**
  * 强制关闭软键盘
  */
 public void closeKeyboard(Context context) {
  InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
  if (imm.isActive()) {
   //如果开启
   imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
     InputMethodManager.HIDE_NOT_ALWAYS);
   //关闭软键盘,开启方法相同,这个方法是切换开启与关闭状态的
  }
 }
}

2、activity_map.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#e9e7ef"
 android:orientation="vertical"
 tools:context="com.hzstz.mymanager.MapActivity">
 <LinearLayout
  android:layout_width="match_parent"
  android:layout_height="50dp"
  android:layout_weight="1"
  android:background="#009dff"
  android:orientation="horizontal">
  <ImageView
   android:id="@+id/back"
   android:layout_width="30dp"
   android:layout_height="25dp"
   android:layout_gravity="center_vertical"
   android:layout_weight="6"
   android:src="@drawable/left" />
  <TextView
   android:id="@+id/title"
   android:layout_width="wrap_content"
   android:layout_height="match_parent"
   android:layout_weight="80"
   android:gravity="center"
   android:text="@string/app_name"
   android:textColor="#000"
   android:textSize="25dp"
   android:visibility="visible" />
  <FrameLayout
   android:id="@+id/searchLayout"
   android:layout_width="wrap_content"
   android:layout_height="match_parent"
   android:layout_weight="5">
   <EditText
    android:id="@+id/search_input"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:layout_gravity="center_vertical"
    android:layout_marginTop="2dp"
    android:hint="@string/app_name"
    android:paddingStart="40dp"
    android:visibility="gone" />
   <ImageView
    android:id="@+id/search"
    android:layout_width="35dp"
    android:layout_height="35dp"
    android:layout_gravity="center_vertical"
    android:paddingStart="10dp"
    android:src="@drawable/search" />
  </FrameLayout>
  <Button
   android:id="@+id/search_go_btn"
   android:layout_width="wrap_content"
   android:layout_height="match_parent"
   android:background="@drawable/cling_button_normal"
   android:text="搜索"
   android:textColor="#fff"
   android:visibility="gone" />
  <ImageView
   android:id="@+id/success"
   android:layout_width="30dp"
   android:layout_height="30dp"
   android:layout_gravity="center_vertical"
   android:layout_margin="5dp"
   android:layout_weight="1"
   android:src="@drawable/yes"
   android:visibility="visible" />
 </LinearLayout>
 <com.amap.api.maps.MapView
  android:id="@+id/map"
  android:layout_width="match_parent"
  android:layout_height="750dp"
  android:layout_weight="100" />
 <ListView
  android:id="@+id/ll"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_weight="90"
  android:background="#ffffff" />
</LinearLayout>

3、location.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="#fff"
 android:padding="10dp"
 android:orientation="horizontal">
 <LinearLayout
  android:layout_width="match_parent"
  android:orientation="vertical"
  android:layout_weight="100"
  android:layout_height="wrap_content">
  <TextView
   android:id="@+id/name"
   android:textSize="20dp"
   android:text="大会的反馈撒"
   android:textColor="#000"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content" />
  <TextView
   android:id="@+id/sub"
   android:textSize="15dp"
   android:text="大会的反馈撒"
   android:textColor="#808080"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content" />
 </LinearLayout>
 <ImageView
  android:id="@+id/yes"
  android:layout_width="30dp"
  android:layout_height="30dp"
  android:layout_gravity="center"
  android:src="@drawable/location"/>
</LinearLayout>

总结

以上所述是小编给大家介绍的Android基于高德地图poi的仿微信获取位置功能实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI