仿百度外卖3_7_1百度地图拖动定位,显示附近地址poi提示搜索

原创 2016年06月01日 14:46:22



前页:这里用到的sdk包就不介绍了在百度api里面去下载就好了,然后就正式看对mapview的使用以及拖动地图控件时候对地图中间的红色箭头的处理。



1.先看下当前页面的布局文件:R.layout.activity_more_address,由一个mapview和listview组成,上面的编辑框是由AutoCompleteTextView自动提示输入框组成。

<?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="match_parent"
    android:background="@color/white"
    android:clipToPadding="false"
    android:fitsSystemWindows="true"
    android:orientation="vertical" >


    <RelativeLayout
        android:id="@+id/rl_search"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:background="@color/tab" >


        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="30dp"
            android:layout_centerInParent="true"
            android:layout_marginLeft="6dp"
            android:layout_marginRight="12dp"
            android:layout_marginTop="6dp"
            android:layout_toRightOf="@+id/iv_left"
            android:background="@color/bg_mine" >


            <ImageView
                android:id="@+id/iv_search"
                android:layout_width="26dp"
                android:layout_height="26dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="6dp"
                android:paddingRight="6dp"
                android:src="@drawable/search_icon_blac" />


            <AutoCompleteTextView
                android:id="@+id/et_search"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_toRightOf="@+id/iv_search"
                android:background="@color/bg_mine"
                android:gravity="center_vertical"
                android:hint="请输入您的收货地址"
                android:paddingLeft="2dp"
                android:singleLine="true"
                android:textColor="@color/black"
                android:textSize="14sp" />
        </RelativeLayout>


        <ImageView
            android:id="@+id/iv_left"
            style="@style/head_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="6dp"
            android:padding="14dp"
            android:src="@drawable/arrow_left" />
    </RelativeLayout>


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="280dp"
        android:orientation="vertical"
        android:visibility="visible" >


        <com.baidu.mapapi.map.MapView
            android:id="@+id/map"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/white"
            android:onClick="true" >
        </com.baidu.mapapi.map.MapView>


        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:background="@color/transparent"
            android:src="@drawable/gps_red" />
    </RelativeLayout>


    <ListView
        android:id="@+id/lv_near_address"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:cacheColorHint="#00000000"
        android:descendantFocusability="beforeDescendants"
        android:fastScrollEnabled="true"
        android:scrollbars="none" />


</LinearLayout>


2.然后就是拖动的地址活动界面MoreAddressActivity,拖动地图的时候中间的红色gps箭头指向当前的地址,下面的listview会根据当前经纬度反地理编码拿到附近的地址列表,第一个当然显示的是gps箭头所指向位置,点击listview中的item之后,会返回所要拿到的地图位置。


package cn.wifi.bryant.ttelife;


import java.util.List;


import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.umeng.analytics.MobclickAgent;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.wifi.bryant.ttelife.application.RequestManager;
import cn.wifi.bryant.ttelife.utils.SystemBarTintManager;
import cn.wifi.bryant.ttelife.utils.TtelifeLog;


public class MoreAddressActivity extends Activity implements OnClickListener, OnGetSuggestionResultListener,
OnMapStatusChangeListener, BDLocationListener, OnGetGeoCoderResultListener {
private ImageView iv_left;
protected static final String TAG = "MoreAddressActivity";
protected static final int REQUEST_OK = 0;
private ListView lv_near_address;
private SuggestionSearch mSuggestionSearch = null;
private BaiduMap mBaiduMap = null;
private double latitude;
private double longitude;
/**
* 搜索关键字输入窗口
*/
private AutoCompleteTextView keyWorldsView = null;
private ArrayAdapter<String> sugAdapter = null;
private int load_Index = 0;
private PoiSearchAdapter adapter;
private MapView map;
private MyLocationConfiguration.LocationMode mCurrentMode;
private LocationClient mLocClient;
private GeoCoder geoCoder;
private String city;
private boolean isFirstLoc = true;
private LatLng locationLatLng;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_more_address);
initData();
setStatusBarColor();
}


private void initData() {
map = (MapView) findViewById(R.id.map);
mBaiduMap = map.getMap();
MapStatus mapStatus = new MapStatus.Builder().zoom(15).build();
MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapStatus);
mBaiduMap.setMapStatus(mMapStatusUpdate);
// 地图状态改变相关监听
mBaiduMap.setOnMapStatusChangeListener(this);
// 开启定位图层
mBaiduMap.setMyLocationEnabled(true);
// 定位图层显示方式
mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, null));
mLocClient = new LocationClient(this);
// 注册定位监听
mLocClient.registerLocationListener(this);
// 定位选项
LocationClientOption option = new LocationClientOption();
/**
* coorType - 取值有3个: 返回国测局经纬度坐标系:gcj02 返回百度墨卡托坐标系 :bd09 返回百度经纬度坐标系
* :bd09ll
*/
option.setCoorType("bd09ll");
// 设置是否需要地址信息,默认为无地址
option.setIsNeedAddress(true);
// 设置是否需要返回位置语义化信息,可以在BDLocation.getLocationDescribe()中得到数据,ex:"在天安门附近",
// 可以用作地址信息的补充
option.setIsNeedLocationDescribe(true);
// 设置是否需要返回位置POI信息,可以在BDLocation.getPoiList()中得到数据
option.setIsNeedLocationPoiList(true);
/**
* 设置定位模式 Battery_Saving 低功耗模式 Device_Sensors 仅设备(Gps)模式 Hight_Accuracy
* 高精度模式
*/
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
// 设置是否打开gps进行定位
option.setOpenGps(true);
// 设置扫描间隔,单位是毫秒 当<1000(1s)时,定时定位无效
option.setScanSpan(1000);
// 设置 LocationClientOption
mLocClient.setLocOption(option);
// 开始定位
mLocClient.start();
lv_near_address = (ListView) findViewById(R.id.lv_near_address);
// 初始化搜索模块,注册搜索事件监听
mSuggestionSearch = SuggestionSearch.newInstance();
mSuggestionSearch.setOnGetSuggestionResultListener(this);
keyWorldsView = (AutoCompleteTextView) findViewById(R.id.et_search);
sugAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line);
keyWorldsView.setAdapter(sugAdapter);
/**
* 当输入关键字变化时,动态更新建议列表
*/
keyWorldsView.addTextChangedListener(new TextWatcher() {


@Override
public void afterTextChanged(Editable arg0) {
}


@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {


}


@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
if (cs.length() <= 0) {
return;
}
String city = "深圳";
/**
* 使用建议搜索服务获取建议列表,结果在onSuggestionResult()中更新
*/
mSuggestionSearch.requestSuggestion((new SuggestionSearchOption()).keyword(cs.toString()).city(city));
}
});
keyWorldsView.setOnItemClickListener(new OnItemClickListener() {


@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String address = arg0.getItemAtPosition(arg2).toString();
TtelifeLog.i(TAG, "address.toString()" + address.toString());
Intent intentAddress = new Intent();
intentAddress.putExtra("selectAddress", keyWorldsView.getText().toString());
setResult(RESULT_OK, intentAddress);
finish();
}
});
iv_left = (ImageView) findViewById(R.id.iv_left);
iv_left.setOnClickListener(this);
}


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

* @param poiResult
*/


@Override
protected void onDestroy() {
super.onDestroy();
mLocClient.stop();
mBaiduMap.setMyLocationEnabled(false);
map.onDestroy();
if (geoCoder != null) {
geoCoder.destroy();
}
map = null;
mSuggestionSearch.destroy();
RequestManager.cancelRequest(this);
}


@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}


@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}


@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_left:
finish();
break;


default:
break;
}
}


public void onResume() {
super.onResume();
map.onResume();
if (getIntent().getStringExtra("latitude") != null && (!"".equals(getIntent().getStringExtra("latitude")))) {
latitude = Double.parseDouble(getIntent().getStringExtra("latitude"));
longitude = Double.parseDouble(getIntent().getStringExtra("longitude"));
TtelifeLog.i(TAG, "latitude" + latitude);
}
MobclickAgent.onResume(this);
}


public void onPause() {
super.onPause();
map.onPause();
MobclickAgent.onPause(this);
}


private void setStatusBarColor() {
Window window = getWindow();
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
window.setAttributes(params);
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setTintColor(getResources().getColor(R.color.tab));
}


public void onGetPoiDetailResult(PoiDetailResult result) {
if (result.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(MoreAddressActivity.this, "抱歉,未找到结果", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MoreAddressActivity.this, result.getName() + ": " + result.getAddress(), Toast.LENGTH_SHORT)
.show();
}
}


@Override
public void onGetSuggestionResult(SuggestionResult res) {
if (res == null || res.getAllSuggestions() == null) {
return;
}
sugAdapter.clear();
for (SuggestionResult.SuggestionInfo info : res.getAllSuggestions()) {
if (info.key != null)
sugAdapter.add(info.key + " " + info.city + info.district);
}
sugAdapter.notifyDataSetChanged();
}


class PoiSearchAdapter extends BaseAdapter {


private Context context;
private List<PoiInfo> list;
private ViewHolder holder;


public PoiSearchAdapter(Context context, List<PoiInfo> appGroup) {
this.context = context;
this.list = appGroup;
}


@Override
public int getCount() {
return list.size();
}


@Override
public Object getItem(int location) {
return list.get(location);
}


@Override
public long getItemId(int arg0) {
return arg0;
}


public void addObject(List<PoiInfo> mAppGroup) {
this.list = mAppGroup;
notifyDataSetChanged();
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {


if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.activity_poi_search_item, null);
holder.mpoi_name = (TextView) convertView.findViewById(R.id.mpoiNameT);
holder.mpoi_address = (TextView) convertView.findViewById(R.id.mpoiAddressT);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.mpoi_name.setText(list.get(position).name);
holder.mpoi_address.setText(list.get(position).address);
// Log.i("yxx", "==1=poi===城市:" + poiInfo.city + "名字:" +
// poiInfo.name + "地址:" + poiInfo.address);
return convertView;
}


public class ViewHolder {
public TextView mpoi_name;// 名称
public TextView mpoi_address;// 地址


}


}


@Override
public void onMapStatusChange(MapStatus mapStatus) {


}


@Override
public void onMapStatusChangeFinish(MapStatus mapStatus) {
// 地图操作的中心点
LatLng cenpt = mapStatus.target;
geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(cenpt));
}


@Override
public void onMapStatusChangeStart(MapStatus mapStatus) {


}


@Override
public void onReceiveLocation(BDLocation bdLocation) {
// 如果bdLocation为空或mapView销毁后不再处理新数据接收的位置
if (bdLocation == null || mBaiduMap == null) {
return;
}


// 定位数据
MyLocationData data = new MyLocationData.Builder()
// 定位精度bdLocation.getRadius()
.accuracy(bdLocation.getRadius())
// 此处设置开发者获取到的方向信息,顺时针0-360
.direction(bdLocation.getDirection())
// 经度
.latitude(bdLocation.getLatitude())
// 纬度
.longitude(bdLocation.getLongitude())
// 构建
.build();


// 设置定位数据
mBaiduMap.setMyLocationData(data);


// 是否是第一次定位
if (isFirstLoc) {
isFirstLoc = false;
LatLng ll = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
MapStatusUpdate msu = MapStatusUpdateFactory.newLatLngZoom(ll, 18);
mBaiduMap.animateMapStatus(msu);
}


locationLatLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
// 获取城市,待会用于POISearch
city = bdLocation.getCity();


// 创建GeoCoder实例对象
geoCoder = GeoCoder.newInstance();
// 发起反地理编码请求(经纬度->地址信息)
ReverseGeoCodeOption reverseGeoCodeOption = new ReverseGeoCodeOption();
// 设置反地理编码位置坐标
reverseGeoCodeOption.location(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()));
geoCoder.reverseGeoCode(reverseGeoCodeOption);


// 设置查询结果监听者
geoCoder.setOnGetGeoCodeResultListener(this);
}


@Override
public void onGetGeoCodeResult(GeoCodeResult arg0) {


}


// 拿到变化地点后的附近地址
@Override
public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
final List<PoiInfo> poiInfos = reverseGeoCodeResult.getPoiList();
TtelifeLog.i(TAG, "这里的值:" + poiInfos);
if (poiInfos != null && !"".equals(poiInfos)) {
PoiAdapter poiAdapter = new PoiAdapter(MoreAddressActivity.this, poiInfos);
lv_near_address.setAdapter(poiAdapter);
lv_near_address.setOnItemClickListener(new OnItemClickListener() {


@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = poiInfos.get(position).name.toString();
Intent intent = new Intent();
intent.putExtra("selectAddress", name);
setResult(RESULT_OK, intent);
finish();
}
});
}
}


class PoiAdapter extends BaseAdapter {
private Context context;
private List<PoiInfo> pois;
private LinearLayout linearLayout;


PoiAdapter(Context context, List<PoiInfo> pois) {
this.context = context;
this.pois = pois;
}


@Override
public int getCount() {
return pois.size();
}


@Override
public Object getItem(int position) {
return pois.get(position);
}


@Override
public long getItemId(int position) {
return position;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.locationpois_item, null);
linearLayout = (LinearLayout) convertView.findViewById(R.id.locationpois_linearlayout);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (position == 0) {
holder.iv_gps.setImageDrawable(getResources().getDrawable(R.drawable.gps_orange));
holder.locationpoi_name.setTextColor(Color.parseColor("#FF9D06"));
holder.locationpoi_address.setTextColor(Color.parseColor("#FF9D06"));
}
if (position == 0 && linearLayout.getChildCount() < 2) {
ImageView imageView = new ImageView(context);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(32, 32);
imageView.setLayoutParams(params);
imageView.setBackgroundColor(Color.TRANSPARENT);
imageView.setImageResource(R.drawable.gps_grey);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
linearLayout.addView(imageView, 0, params);
holder.locationpoi_name.setTextColor(Color.parseColor("#FF5722"));
}
PoiInfo poiInfo = pois.get(position);
holder.locationpoi_name.setText(poiInfo.name);
holder.locationpoi_address.setText(poiInfo.address);
return convertView;
}


class ViewHolder {
ImageView iv_gps;
TextView locationpoi_name;
TextView locationpoi_address;


ViewHolder(View view) {
locationpoi_name = (TextView) view.findViewById(R.id.locationpois_name);
locationpoi_address = (TextView) view.findViewById(R.id.locationpois_address);
iv_gps = (ImageView) view.findViewById(R.id.iv_gps);
}
}
}
}



3.后面的两个布局文件R.layout.activity_poi_search_item和R.layout.locationpois_item,分别是自动提示检索的item界面和listview的item界面

<?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="match_parent"
    android:orientation="vertical"
    android:padding="5dp" >


    <LinearLayout
        android:id="@+id/locationpois_linearlayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal" >


        <ImageView
            android:id="@+id/iv_gps"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="4dp"
            android:src="@drawable/gps_grey" />


        <TextView
            android:id="@+id/locationpois_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="6dp"
            android:text="威盛大厦"
            android:textColor="#4A4A4A"
            android:textSize="14sp" />
    </LinearLayout>


    <TextView
        android:id="@+id/locationpois_address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="4dp"
        android:text="威盛大厦"
        android:textColor="@color/darkgray"
        android:textSize="12sp" />


</LinearLayout>

点击下载源码:点击打开链接

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Tinker 接入指南

Tinker 接入指南 gradle接入 gradle是推荐的接入方式,在gradle插件tinker-patch-gradle-plugin中我们帮你完成proguard、multiDe...

Android 热修复 Tinker接入及源码浅析

一、概述 放了一个大长假,happy,先祝大家2017年笑口常开。 假期中一行代码没写,但是想着马上要上班了,赶紧写篇博客回顾下技能,于是便有了本文。 热修复这项技术,基本上已经成为项目比较重要...

微信Android热更新Tinker使用详解(by 星空武哥)

转载请标注原创地址: Tinker是什么 Tinker是微信官方的Android热补丁解决方案,它支持动态下发代码、So库以及资源,让应用能够在不需要重新安装的情况下实现更新。当然,你也可以使用...

百度地图拖动定位

(1)首先关闭定位图层,否则影响地图拖动    mBaiduMap.setMyLocationEnabled(false);//关键点,必须设置  (2)设置marker    BitmapDescr...
  • myrssq
  • myrssq
  • 2016-07-07 13:52
  • 1783

百度地图 点击和标注拖拽后的经纬度

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  Hello, World        html{heigh...
  • lybwwp
  • lybwwp
  • 2012-10-30 11:18
  • 10640

部分国行Android手机缺少谷歌GMS服务包导致HTML5 Geolocation无法定位的问题

最近项目上用到HTML5的geolocation用于定位,用Chrome和手头的手机测试好好的功能,到终端用户那里反馈一些手机不能定位,最后确定出是部分三星、摩托的部分国行Android手机“阉割”了...

使用百度地图实现拖动定位、搜索定位

该代码主要的技术点: ==>获取百度地图key,也就是ak; ==>拖动定位,经纬度、详细地址 ==>搜索定位,根据所搜索得地址进行地图地位,精确定位。 具体的实现代码: !DOCTYPE ...

百度地图api--拖动地图显示经纬度与显示当前位置

一.首先引入所申请的ak密钥 二.简单样式处理一下body, html{width: 100%;height: 100%;margin:0;font-family:"微软雅黑";}#allmap{he...

百度地图api--拖动地图,弹出经纬度

一.首先引入所申请的ak密钥 二.简单样式处理一下body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)