读完后,接着看看这篇博文吧,这篇文章是将前俩篇的搜索和定位进行了简单地整合,并在点击搜索到的标志处可以简单地显示所在位置的名称。注:这里的给出的代码都是在之前的项目上新增的哦~~~
新建linemap.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="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="@+id/edit_linemap"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1" />
<Button
android:id="@+id/btn1_linemap"
android:text="搜索"
android:layout_width="wrap_content"
android:layout_height="match_parent"/>
<Button
android:id="@+id/btn2_linemap"
android:text="定位"
android:layout_width="wrap_content"
android:layout_height="match_parent"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="盐城"
android:id="@+id/radio1"
/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="上海"
android:id="@+id/radio2"
/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="南京"
android:id="@+id/radio3"
/>
</LinearLayout>
<com.baidu.mapapi.map.MapView android:id="@+id/linemap_bmapsView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true" />
</LinearLayout>
新建pop_window_text.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="match_parent"
android:orientation="vertical"
android:background="@drawable/popup" >
<TextView
android:id="@+id/tv_pop_window_item"
android:layout_width="wrap_content"
android:layout_height="39px"
android:text="Text"
android:textSize="16dp"
android:gravity="center"
android:background="#383838"
android:textColor="#fff"
/>
</LinearLayout>
新建activity代码如下:
package com.diecolor;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKEvent;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.PoiOverlay;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.map.TransitOverlay;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPlanNode;
import com.baidu.mapapi.search.MKPoiInfo;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKShareUrlResult;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class LineMapActivity extends Activity{
GeoPoint geoPoint;
Button btn1,btn2;
EditText editText;
RadioButton radioButton1,radioButton2,radioButton3;
BMapManager mBMapMan = null;
MapView mMapView = null;
MKSearch mkSearch=null;
String city;
Handler handler;
ProgressDialog progressDialogCity;
PoiOverlay poiOverlay;//兴趣点图层
MyLocationOverlay myLocationOverlay;//定位图层
public LocationClient mLocationClient=null;
public BDLocationListener myListener=new MyLocationListener();
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mBMapMan=new BMapManager(getApplication());
mBMapMan.init("4b605b48b3062e4687d0ada2ecd65a8e", null);
//注意:请在试用setContentView前初始化BMapManager对象,否则会报错
setContentView(R.layout.linemap_main);
mMapView=(MapView)findViewById(R.id.linemap_bmapsView);
btn1=(Button) findViewById(R.id.btn1_linemap);
btn2=(Button) findViewById(R.id.btn2_linemap);
radioButton1=(RadioButton) findViewById(R.id.radio1);
radioButton2=(RadioButton) findViewById(R.id.radio2);
radioButton3=(RadioButton) findViewById(R.id.radio3);
editText=(EditText) findViewById(R.id.edit_linemap);
mMapView.setBuiltInZoomControls(true);
MapController mapController=mMapView.getController();//得到mMapView控制权,可以用它控制盒驱动平移和缩放
GeoPoint point=new GeoPoint((int)(39.915* 1E6),(int)(116.404* 1E6));//用给定的经纬度构造一个GeoPoint,单位是微度 (度 * 1E6)
mapController.setCenter(point);//设置地图中心点
mapController.setZoom(12);//设置地图zoom级别
//初始化 查询
mkSearch=new MKSearch();
mkSearch.init(mBMapMan, new MySearchListener());//注意,MKSearchListener只支持一个,以最后一次设置为准
mLocationClient=new LocationClient(getApplicationContext());//声明LocationClient类
mLocationClient.registerLocationListener(myListener);//注册监听函数
mMapView.getController().enableClick(true);//否则不会调用mklistner
LocationClientOption option=new LocationClientOption();
option.setOpenGps(true);
option.setAddrType("all");//返回的定位结果包含地址信息
option.setCoorType("bd0911");//返回的定位结果是百度经纬度,默认值gcj02
option.setScanSpan(LocationClientOption.MIN_SCAN_SPAN);//设置发起定位请求的间隔时间为5000ms
option.disableCache(true);//禁止启用缓存定位
option.setPoiDistance(1000);//poi查询距离
option.setPoiExtraInfo(true);//是否需要POI的电话和地址等详细信息
mLocationClient.setLocOption(option);
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mLocationClient.start();
mMapView.getController().setZoom(15);
if (mLocationClient!=null&&mLocationClient.isStarted()) {
mLocationClient.requestLocation();
}
else {
Log.d("LocSDK3", "location is null or not started");
//兴趣点
if (mLocationClient!=null&&mLocationClient.isStarted()) {
mLocationClient.requestPoi();
}
}
}});
//初次定位
if (mLocationClient != null && mLocationClient.isStarted())
mLocationClient.requestLocation();
else
Log.d("LocSDK3", "locClient is null or not started");
//兴趣点
if (mLocationClient != null && mLocationClient.isStarted())
mLocationClient.requestPoi();
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//得到当前的地理信息
GeoPoint centerPoint=mMapView.getMapCenter();
mkSearch.reverseGeocode(centerPoint);//得到城市
//异步处理
progressDialogCity=new ProgressDialog(LineMapActivity.this);
progressDialogCity.setCancelable(true);
progressDialogCity.setTitle("查询--"+editText.getText().toString());
progressDialogCity.setMessage("正在查询,请稍候.............");
progressDialogCity.show();
}
});
handler=new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what==0x001) {
progressDialogCity.dismiss();//消失
if (city==null||city.equals("")) {
Toast.makeText(LineMapActivity.this, "城市信息获取失败",3000).show();
return;
}
mkSearch.poiSearchInCity(city, editText.getText().toString());
}
}
};
//添加listener
// mMapView.regMapViewListener(mBMapMan, new MapViewListener());
}
class MyLocationListener implements BDLocationListener{
@Override
public void onReceiveLocation(BDLocation location) {
// TODO Auto-generated method stub
GeoPoint geoPoint=new GeoPoint((int)(location.getLatitude()*1E6),(int)(location.getLongitude()*1E6));
/* MyLocationOverlay只负责显示我的位置,,
* 将获取的位置数据放在一个LocationData结构中并用该结构设置MyLcationOverlay的数据源,
* 即可创建MyLocationOverlay。*/
MyLocationOverlay myLocationOverlay=new MyLocationOverlay(mMapView);
LocationData locationData=new LocationData();//将获取的位置数据放在一个LocationData结构中
locationData.latitude=location.getLatitude();
locationData.longitude=location.getLongitude();
locationData.direction=2.0f;
myLocationOverlay.setData(locationData);//设置MyLcationOverlay的数据源
mMapView.getOverlays().clear();
mMapView.getOverlays().add(myLocationOverlay);
if (poiOverlay!=null) {
mMapView.getOverlays().add(poiOverlay);
}
mMapView.refresh();//在更新地图覆盖物后,需调用MapView.refresh() 使更新生效
mMapView.getController().animateTo(geoPoint);
}
@Override
public void onReceivePoi(BDLocation arg0) {
// TODO Auto-generated method stub
}
}
public class MySearchListener implements MKSearchListener{
/*reverseGeocode和geocode的返回结果在都在MKSearchListener里的onGetAddrResult方法中,
* 具体区分是逆地址解析的结果还是地址解析的结果需要判断MKAddrInfo中的type字段,
type字段为MKAddrInfo.MK_GEOCODE的是地理编码的结果、type字段为MKAddrInfo.MK_REVERSEGEOCODE的是逆地理编码的结果
*/
@Override
public void onGetAddrResult(MKAddrInfo res, int error) {
// TODO Auto-generated method stub
if (error != 0) {
String str = String.format("错误号:%d", error);
Toast.makeText(LineMapActivity.this, str, Toast.LENGTH_LONG).show();
return;
}
//地图移动到该点
// mMapView.getController().animateTo(res.geoPt);
if (res.type == MKAddrInfo.MK_GEOCODE) {
//地理编码:通过地址检索坐标点
String strInfo = String.format("纬度:%f 经度:%f", res.geoPt.getLatitudeE6()/1e6, res.geoPt.getLongitudeE6()/1e6);
Toast.makeText(LineMapActivity.this, strInfo, Toast.LENGTH_LONG).show();
}
if (res.type == MKAddrInfo.MK_REVERSEGEOCODE) {
//反地理编码:通过坐标点检索详细地址及周边poi
city= res.addressComponents.city;
Toast.makeText(LineMapActivity.this, city, Toast.LENGTH_LONG).show();
}
//查询完成发消息
Message message=new Message();
message.what=0x001;
handler.sendMessage(message);
}
@Override
public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetDrivingRouteResult(MKDrivingRouteResult arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetPoiDetailSearchResult(int arg0, int arg1) {
// TODO Auto-generated method stub
if (arg1 != 0) {
Toast.makeText(LineMapActivity.this, "抱歉,未找到结果",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LineMapActivity.this, "成功,查看详情页面",
Toast.LENGTH_SHORT).show();
}
}
public void onGetPoiResult(MKPoiResult res, int type, int error) {
// TODO Auto-generated method stub
// 错误号可参考MKEvent中的定义
if ( error == MKEvent.ERROR_RESULT_NOT_FOUND){
Toast.makeText(LineMapActivity.this, "抱歉,未找到结果",Toast.LENGTH_LONG).show();
return ;
}
else if (error != 0 || res == null) {
Toast.makeText(LineMapActivity.this, "搜索出错啦..", Toast.LENGTH_LONG).show();
return;
}
// 将poi结果显示到地图上
PlacePoiOverlay poiOverlay = new PlacePoiOverlay(LineMapActivity.this, mMapView);
poiOverlay.setData(res.getAllPoi()); //把查询结果 放置到层中
mMapView.getOverlays().clear(); //清空以前查询的结果
mMapView.getOverlays().add(poiOverlay); //添加搜索结果的层
mMapView.refresh(); //刷新
//当ePoiType为2(公交线路)或4(地铁线路)时, poi坐标为空
for (MKPoiInfo mk : res.getAllPoi()) {
if (mk.pt!=null) {
mMapView.getController().animateTo(mk.pt);
break;
}
}
}
@Override
public void onGetShareUrlResult(MKShareUrlResult arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onGetTransitRouteResult(MKTransitRouteResult result, int error) {
// TODO Auto-generated method stub
if (error!=0) {
Toast.makeText(LineMapActivity.this, "没有公交线路!", 3000).show();
return;
}
if (result==null) {
Toast.makeText(LineMapActivity.this, "没有公交线路!", 3000).show();
return;
}
TransitOverlay transitOverlay=new TransitOverlay(LineMapActivity.this, mMapView);
transitOverlay.setData(result.getPlan(0));
mMapView.getOverlays().clear();
if (myLocationOverlay!=null) {
mMapView.getOverlays().add(myLocationOverlay);
}
if (poiOverlay!=null) {
mMapView.getOverlays().add(poiOverlay);
}
mMapView.getOverlays().add(transitOverlay);
mMapView.refresh();
}
@Override
public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {
// TODO Auto-generated method stub
}}
//class MapViewListener implements MKMapViewListener{
//
// @Override
// public void onClickMapPoi(MapPoi poi) {
// // TODO Auto-generated method stub
// //map poi
// GeoPoint geoPoint=poi.geoPt;
// String description=poi.strText;
//
// PopupOverlay popupOverlay=new PopupOverlay(mMapView, new PopupClickListener() {
//
// @Override
// public void onClickedPopup(int arg0) {
// // TODO Auto-generated method stub
//
// }
// });
// Bitmap[] bitmaps=new Bitmap[3];
// try {
// bitmaps[0]=BitmapFactory.decodeStream(getAssets().open("marker1.png"));
// bitmaps[1]=BitmapFactory.decodeStream(getAssets().open("marker2.png"));
// bitmaps[2]=BitmapFactory.decodeStream(getAssets().open("marker3.png"));
// } catch (Exception e) {
// e.printStackTrace();
// }
// popupOverlay.showPopup(bitmaps, geoPoint, 32);
//
// mMapView.getController().animateTo(geoPoint);
// }
//
// @Override
// public void onGetCurrentMap(Bitmap arg0) {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public void onMapAnimationFinish() {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public void onMapLoadFinish() {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public void onMapMoveFinish() {
// // TODO Auto-generated method stub
//
// }}
//自定义 兴趣点层
public class PlacePoiOverlay extends PoiOverlay {
MKSearch mSearch;
public PlacePoiOverlay(Activity activity, MapView mapView) {
super(activity, mapView);
}
//单击气球 弹出窗口
@Override
protected boolean onTap(int i) {
super.onTap(i);
final MKPoiInfo mkPoiInfo = getPoi(i);
PopupOverlay popupOverlay = new PopupOverlay(mMapView,
new PopupClickListener() {
@Override
public void onClickedPopup(int arg0) {
// TODO Auto-generated method stub
if (geoPoint==null) {
Toast.makeText(LineMapActivity.this, "自我定位失败", 2000).show();
return;
}
MKPlanNode start=new MKPlanNode();
start.pt=geoPoint;
MKPlanNode end=new MKPlanNode();
end.pt=mkPoiInfo.pt;
mkSearch.transitSearch(city, start, end);
}
});
Bitmap[] bitmaps = new Bitmap[3];
try {
bitmaps[0] = BitmapFactory.decodeStream(getAssets().open(
"marker1.png"));
// //把XML文件转换成图片
View popview = LayoutInflater.from(LineMapActivity.this)
.inflate(R.layout.pop_window_text, null);// 获取要转换的View资源
TextView TestText = (TextView) popview
.findViewById(R.id.tv_pop_window_item);
TestText.setText(mkPoiInfo.name);// 将每个点的Title在弹窗中以文本形式显示出来
Bitmap popbitmap = convertViewToBitmap(popview);
bitmaps[1] = popbitmap;
bitmaps[2] = BitmapFactory.decodeStream(getAssets().open(
"marker3.png"));
} catch (Exception e) {
e.printStackTrace();
}
popupOverlay.showPopup(bitmaps, mkPoiInfo.pt, 32);
mMapView.getController().animateTo(mkPoiInfo.pt);
return true;
}
}
@Override
protected void onDestroy(){
mMapView.destroy();
if(mBMapMan!=null){
mBMapMan.destroy();
mBMapMan=null;
}
super.onDestroy();
}
@Override
protected void onPause(){
mMapView.onPause();
if(mBMapMan!=null){
mBMapMan.stop();
}
super.onPause();
}
@Override
protected void onResume(){
mMapView.onResume();
if(mBMapMan!=null){
mBMapMan.start();
}
super.onResume();
}
/辅助方法
// 把xml文件转换成图片
public Bitmap convertViewToBitmap(View view) {
view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
return bitmap;
}
}
效果图:
本文的例子比较小,存在一些小错误,还有待完善。。。不过会持续更新的哦~~~欢迎喜欢安卓的亲们提出你们的宝贵意见哦~~~