Android 开发百度地图定位搜索
效果图
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIyVGduV2YfNWawNCM38FdsYkRGZkRG9lcvx2bjxiNx8VZ6l2cs0TPR10dZpXT3FEROBDOsJGcohVYsR2MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZwpmLykTN3ADOzUTM4ATMwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
界面
<RelativeLayout 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"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true" />
<LinearLayout
android:id="@+id/layout_list_address"
android:layout_width="match_parent"
android:layout_height="350dp"
android:paddingTop="63dp"
android:paddingRight="30dp"
android:paddingLeft="30dp"
android:orientation="horizontal"
android:visibility="gone"
>
<ListView
android:id="@+id/list_prov"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="20"
android:background="#f4f4f4"
android:divider="@null"
android:listSelector="@drawable/search_more_mainlistselect"
android:scrollbars="none" />
</LinearLayout>
<RelativeLayout
android:id="@+id/layout_top"
android:layout_width="fill_parent"
android:layout_height="44dp"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:background="@drawable/bg_border_gray_round"
android:elevation="4dp"
android:gravity="center" >
<!-- 搜索 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:gravity="center_vertical"
android:orientation="horizontal" >
<LinearLayout
android:id="@+id/layout_back"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical"
android:paddingLeft="14dp"
android:paddingRight="12dp" >
<ImageView
android:layout_width="14dp"
android:layout_height="16dp"
android:layout_gravity="left|center_vertical"
android:src="@drawable/back" />
</LinearLayout>
<AutoCompleteTextView
android:id="@+id/keyWord"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:focusable="true"
android:hint="请输入关键字"
android:imeOptions="actionDone"
android:maxLength="20"
android:singleLine="true"
android:textColor="#000000"
android:textSize="16.0sp" />
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="8dp"
android:background="#cccccc" />
<TextView
android:id="@+id/text_city_search"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:paddingLeft="10dp"
android:paddingRight="14dp"
android:text="城市"
android:textSize="16sp" />
<LinearLayout
android:layout_margin="5dp"
android:id="@+id/top"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="50dp">
<EditText
android:id="@+id/a"
android:layout_width="0dp"
android:paddingLeft="6dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:hint="城市名"
android:layout_marginRight="5dp"
/>
<EditText
android:id="@+id/b"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
android:layout_weight="2"
android:hint="关联词"
/>
<Button
android:id="@+id/btn"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:background="@drawable/search_glass_item"
android:text=""/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="190dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:gravity="left" >
<ImageView
android:id="@+id/img_dw"
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_gravity="left|center_vertical"
android:src="@drawable/dw" />
<Button
android:id="@+id/btn_save2"
style="@style/button"
android:layout_width="80dp"
android:layout_height="32dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="@drawable/button_1"
android:text="确定"
android:textColor="#ffffff" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/layout_bottom"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="4dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#ffffff"
android:orientation="horizontal"
android:gravity="center">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<TextView
style="@style/text_title"
android:layout_width="0dp"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:text="详细地址"
android:textSize="20dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal"
android:padding="30dp" >
<TextView
android:id="@+id/text_addres"
style="@style/text_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:gravity="left|center_vertical"
android:lineSpacingMultiplier="1.3"
android:text="xx"
android:textSize="20dp"/>
</LinearLayout>
</RelativeLayout>
<ImageView
android:id="@+id/img_dw"
android:layout_width="80dp"
android:layout_height="80dp"
android:paddingBottom="35dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/dt" />
</RelativeLayout>
代码
public class AmapSearchActivity extends Activity {
public MapView mapView = null;
public BaiduMap baiduMap = null;
private TextView text_city;
private ListView list_city;
private ImageView img_dw;
private Button btn_save;
private LinearLayout layout_back;
private BigDecimal lng;
private BigDecimal lat;
private String cityName;
private String address;
private String customerid;
private String userid;
private String service_token;
private String curr_lng;
private String curr_lat;
private double bdlat;
private double bdlng;
public static String curr_dw_city = "";
//
public static String curr_city = "";// 当前选择城市
// 定位相关声明
public LocationClient locationClient = null;
//自定义图标
BitmapDescriptor mCurrentMarker = null;
boolean isFirstLoc = true;// 是否首次定位
private AdapterListViewCustomer adapter;
private BaseServicesllerActivity baseactivity;
private LatLng latLng ;
private AutoCompleteTextView searchText,keyWord;
SuggestionSearch mSuggestionSearch;
PoiSearch mPoiSearch;
private Button btn;
private TextView a,b,text_addres;
private ListView list_prov;
private String result;
private LinearLayout layout_list_address;
private String addres;
private RelativeLayout layout_bottom;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 在使用SDK各组件之前初始化context信息,传入ApplicationContext
// 注意该方法要再setContentView方法之前实现
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_map);
mapView = (MapView) this.findViewById(R.id.bmapView); // 获取地图控件引用
baiduMap = mapView.getMap();
//开启定位图层
baiduMap.setMyLocationEnabled(true);
locationClient = new LocationClient(getApplicationContext()); // 实例化LocationClient类
locationClient.registerLocationListener(myListener); // 注册监听函数
this.setLocationOption(); //设置定位参数
locationClient.start(); // 开始定位
mSuggestionSearch = SuggestionSearch.newInstance();
mSuggestionSearch.setOnGetSuggestionResultListener(listener);
initView();
}
public BDLocationListener myListener = new BDLocationListener() {
@Override
public void onReceiveLocation(BDLocation location) {
// map view 销毁后不在处理新接收的位置
if (location == null || mapView == null)
return;
MyLocationData locData = new MyLocationData.Builder()
.accuracy(location.getRadius())
// 此处设置开发者获取到的方向信息,顺时针0-360
.direction(100).latitude(location.getLatitude())
.longitude(location.getLongitude()).build();
baiduMap.setMyLocationData(locData); //设置定位数据
// cityName=location.getCity();
if (isFirstLoc) {
isFirstLoc = false;
LatLng ll = new LatLng(location.getLatitude(),location.getLongitude());
lat = new BigDecimal(location.getLatitude());
lng= new BigDecimal(location.getLongitude());
curr_lng=Common.ObjectToStr(location.getLongitude());
curr_lat=Common.ObjectToStr(location.getLatitude());
MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, 16); //设置地图中心点以及缩放级别
baiduMap.animateMapStatus(u);
latLng = new LatLng(location.getLatitude(), location.getLongitude());
cityName = location.getCity();
text_city.setText(location.getCity());
if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
// gps定位成功
} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
// 网络定位成功
} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
// 离线定位成功,离线定位结果也是有效的
} else if (location.getLocType() == BDLocation.TypeServerError) {
// 服务端网络定位失败,可以反馈IMEI号和大体定位时间到[email protected],会有人追查原因
result = "服务端网络定位失败";
ToastUtil.show(AmapSearchActivity.this,result);
} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
// 网络不同导致定位失败,请检查网络是否通畅
result = "网络不同导致定位失败,请检查网络是否通畅";
ToastUtil.show(AmapSearchActivity.this,result);
} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
// 无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机
result = "无法获取有效定位,请开启定位权限";
ToastUtil.show(AmapSearchActivity.this,result);
}
//获取地址名
GeoCoder mSearch = GeoCoder.newInstance();
mSearch.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
@Override
public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
}
@Override
public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
addres=reverseGeoCodeResult.getAddress();
text_addres.setText(addres);
}
});
//下面是传入对应的经纬度
mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(new LatLng(location.getLatitude(),location.getLongitude())));
}
}
public void onConnectHotSpotMessage(String arg0, int arg1) {
// TODO Auto-generated method stub
}
};
private void initView() {
list_city = (ListView) findViewById(R.id.list_city);
text_addres= (TextView) findViewById(R.id.text_addres);
text_city = (TextView) findViewById(R.id.text_city_search);
layout_back= (LinearLayout) findViewById(R.id.layout_back);
layout_bottom=(RelativeLayout)findViewById(R.id.layout_bottom);
btn = (Button) findViewById(R.id.btn);
a = (TextView) findViewById(R.id.a);
keyWord = (AutoCompleteTextView)findViewById(R.id.keyWord);
layout_list_address=(LinearLayout)findViewById(R.id.layout_list_address);
list_prov=(ListView) findViewById(R.id.list_prov);
///
Intent intent = getIntent();
customerid = intent.getStringExtra("customerid");
userid = intent.getStringExtra("userid");
String slat = intent.getStringExtra("lat");
String slng = intent.getStringExtra("lng");
bdlat=Common.ObjectToDouble(slat);
bdlng=Common.ObjectToDouble(slng);
service_token = intent.getStringExtra("service_token");
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSuggestionSearch = SuggestionSearch.newInstance();
mSuggestionSearch.setOnGetSuggestionResultListener(listener);
mSuggestionSearch.requestSuggestion((new SuggestionSearchOption())
.keyword(keyWord.getText().toString())
.city(text_city.getText().toString()));
}
});
text_city.setText(cityName);
text_city.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AmapSearchActivity.this,
SelectCityActivity.class);
intent.putExtra("cityName", cityName);
AmapSearchActivity.this.startActivityForResult(intent,SelectCityActivity.CITY_REQUESTCODE);
}
});
//返回
layout_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("address", " ");
setResult(RESULT_OK, intent);
AmapSearchActivity.this.finish();
}
});
//回到当前位置
img_dw = (ImageView) findViewById(R.id.img_dw);
img_dw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLng(latLng);
baiduMap.animateMapStatus(mapStatusUpdate);
}
});
//
baiduMap.setOnMapStatusChangeListener(new OnMapStatusChangeListener() {
//地图状态开始改变。
public void onMapStatusChangeStart(MapStatus status) {
}
//地图状态改变结束
public void onMapStatusChangeFinish(MapStatus status) {
//改变结束之后,获取地图可视范围的中心点坐标
LatLng latLng = status.target;
//拿到经纬度之后,就可以反地理编码获取地址信息了
lat = new BigDecimal(latLng.latitude);
lng= new BigDecimal(latLng.longitude);
double latt=latLng.latitude;
double lngg=latLng.longitude;
//获取地址名
GeoCoder mSearch = GeoCoder.newInstance();
mSearch.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
@Override
public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
}
@Override
public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
addres=reverseGeoCodeResult.getAddress();
text_addres.setText(addres);
}
});
//下面是传入对应的经纬度
mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(new LatLng(latt, lngg)));
}
//地图状态变化中
public void onMapStatusChange(MapStatus status) {
}
public void onMapStatusChangeStart(MapStatus arg0, int arg1) {
// TODO Auto-generated method stub
}
});
//点击提交定位
btn_save = (Button) findViewById(R.id.btn_save2);
btn_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
up_customerid(customerid);
}
});
searchText = (AutoCompleteTextView)findViewById(R.id.keyWord);
searchText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
mSuggestionSearch.requestSuggestion((new SuggestionSearchOption())
.keyword(keyWord.getText().toString())
.city(text_city.getText().toString()));
layout_list_address.setVisibility(View.VISIBLE);
layout_bottom.setVisibility(View.VISIBLE);
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
搜索定位
//监听
OnGetSuggestionResultListener listener = new OnGetSuggestionResultListener() {
public void onGetSuggestionResult(SuggestionResult res) {
if (res == null || res.getAllSuggestions() == null) {
// Toast.makeText(AmapSearchActivity.this, "未找到结果", Toast.LENGTH_LONG).show();
return;
//未找到相关结果
}else
{
List<SuggestionResult.SuggestionInfo> resl=res.getAllSuggestions();
BaiduAdapter myAdapter = new BaiduAdapter(resl,getApplicationContext());
list_prov.setAdapter(myAdapter);
list_prov.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SuggestionResult.SuggestionInfo suggestionInfo = (SuggestionResult.SuggestionInfo)parent.getItemAtPosition(position);
searchText.setText(suggestionInfo.city + suggestionInfo.district + suggestionInfo.key);
/* MyLocationData.Builder locData = new MyLocationData.Builder();
locData.direction(100);
locData.latitude(suggestionInfo.pt.latitude);
locData.longitude(suggestionInfo.pt.longitude);
baiduMap.setMyLocationData(locData.build());*/
//ToastUtil.show(AmapSearchActivity.this,suggestionInfo.pt.latitude+"仅"+suggestionInfo.pt.longitude);
try{
LatLng ff = new LatLng(suggestionInfo.pt.latitude,suggestionInfo.pt.longitude);
MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLng(ff);
baiduMap.animateMapStatus(mapStatusUpdate);
layout_list_address.setVisibility(View.GONE);
}
catch (Exception e){
ToastUtil.show(AmapSearchActivity.this,"请输入详细地址查找");
}
}
});
}
}
};
//城市
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SelectCityActivity.CITY_REQUESTCODE) {
// 重选城市
if (data != null) {
try {
String city = data.getExtras().getString("cityName");
if (city.trim().length() > 0) {
curr_city = city;
text_city.setText(curr_city);
}
} catch (Exception e) {
ToastUtil.show(AmapSearchActivity.this, e.getMessage());
e.printStackTrace();
}
}
}
}
// 三个状态实现地图生命周期管理
@Override
protected void onDestroy() {
//退出时销毁定位
locationClient.stop();
baiduMap.setMyLocationEnabled(false);
// TODO Auto-generated method stub
super.onDestroy();
mapView.onDestroy();
mapView = null;
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mapView.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* 设置定位参数
*/
private void setLocationOption() {
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true); // 打开GPS
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 设置定位模式
option.setCoorType("bd09ll"); // 返回的定位结果是百度经纬度,默认值gcj02
option.setScanSpan(5000); // 设置发起定位请求的间隔时间为5000ms
option.setIsNeedAddress(true); // 返回的定位结果包含地址信息
option.setNeedDeviceDirect(true); // 返回的定位结果包含手机机头的方向
locationClient.setLocOption(option);
}
///手动定位
private void up_customerid(String customerid) {
// ///
/* final Dialog loadingDialog = LoadingDialog.createLoadingDialog(
AmapSearchActivity.this, "加载中..");
loadingDialog.setCanceledOnTouchOutside(false);
loadingDialog.show();*/
RequestParams params = new RequestParams(com.data.Config.requestURL
+ "/serviceseller.ashx");
params.addBodyParameter("lat", lat+"");
params.addBodyParameter("lng", lng+"");
params.addBodyParameter("curr_lng", curr_lng);
params.addBodyParameter("curr_lat", curr_lat);
params.addBodyParameter("customerid", customerid);
params.addBodyParameter("ac", "update_customer_lnglat");
params.addBodyParameter("userid", userid);
params.addBodyParameter("address", addres);
params.addBodyParameter("service_token",service_token);
String timestamp = Auth.getTimestamp();
params.addBodyParameter("timestamp", timestamp);
//ToastUtil.show(AmapSearchActivity.this, curr_lng + "," + curr_lat);
String signinfo = "userid=" + userid + "&service_token=" + service_token + "×tamp=" + timestamp + "&customerid=" + customerid;
String sign = Auth.getSign(signinfo, Config.salt);
params.addBodyParameter("sign", sign);
x.http().post(params, new Callback.CommonCallback<String>() {
@Override
public void onSuccess(String data) {
int code = new ResultJsonData(AmapSearchActivity.this).check_result(data);
if(code>0){
ToastUtil.show(AmapSearchActivity.this, "定位成功");
Intent intent = new Intent(AmapSearchActivity.this, ServicesellerCustomerDetailActivity.class);
intent.putExtra("address", addres);
setResult(1, intent);
AmapSearchActivity.this.finish();
EasyMessage.sendMessage("address",addres);
EasyMessage.sendMessage("lat",lat);
EasyMessage.sendMessage("lng",lng);
}
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
Toast.makeText(x.app(), "请求错误:" + ex.getMessage(),
Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
// loadingDialog.dismiss();
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent intent = new Intent();
intent.putExtra("address", " ");
setResult(RESULT_OK, intent);
}
return super.onKeyDown(keyCode, event);
}
class BaiduAdapter extends BaseAdapter {
private Context context;
private List<SuggestionResult.SuggestionInfo> data = new ArrayList<SuggestionResult.SuggestionInfo>();
public BaiduAdapter(List<SuggestionResult.SuggestionInfo> data, Context applicationContext) {
this.context=applicationContext;
this.data=data;
}
public void refreshData(List<SuggestionResult.SuggestionInfo> data) {
this.data = data;
notifyDataSetChanged();
}
@Override
public int getCount() {
return (data != null && data.size() > 0) ? data.size() : 0;
}
@Override
public Object getItem(int arg0) {
return data.get(arg0);
}
@Override
public long getItemId(int arg0) {
return arg0;
}
@SuppressLint("DefaultLocale")
@Override
public View getView(final int position, View currentView, ViewGroup arg2) {
HolderView holderView = null;
if (currentView == null) {
holderView = new HolderView();
currentView = LayoutInflater.from(AmapSearchActivity.this).inflate(R.layout.item_serch, null);
holderView.text_cityname = (TextView) currentView.findViewById(R.id.text_cityname);
currentView.setTag(holderView);
} else {
holderView = (HolderView) currentView.getTag();
resetViewHolder(holderView);
}
if (data.size() != 0) {
final String city = Common.ObjectToStr(data.get(position).city);
String dis = Common.ObjectToStr(data.get(position).district);
String key = Common.ObjectToStr(data.get(position).key);
holderView.text_cityname.setText(city+dis+key);
}
return currentView;
}
protected void resetViewHolder(HolderView holder) {
holder.text_cityname.setText(null);
}
public class HolderView {
private TextView text_cityname;
}
// ///
public void addItem(List<SuggestionResult.SuggestionInfo> item) {
if (data == null)
data = new ArrayList<SuggestionResult.SuggestionInfo>();
data.add((SuggestionResult.SuggestionInfo) item);
}
}
}