Android 百度地图实现POI的搜索(搜索周边)

package com.lbsproject;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.Overlay;
import com.baidu.mapapi.PoiOverlay;
import com.baidu.mapapi.Projection;
import com.lbsproject.LBSProjectActivity.GetOverlay;

public class LBSProjectActivity extends MapActivity {
	protected static final String TAG = null;
	private BMapManager mapManager;
	private MapView mapView;
	private MapController mapController;
	private MKSearch mSearch = null; 
	private GeoPoint geoPoint = new GeoPoint(122084095, 37422006);;
	LocationListener mLocationListener = null;
	MyLocationOverlay mLocationOverlay = null; 
	private EditText editCity;
	private EditText editGeoCodeKey;
	private EditText areaText;
	private GetOverlay getOverlay;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	
		getInitLoc();// 程序打开时候获取当前位置 显示地图上
		mapManager = new BMapManager(getApplication());

		// init方法的第一个参数需填入申请的APIKey
		mapManager.init("2150650BE0DCF874994B845CEC7B60A0518E6AFE", null);
		super.initMapActivity(mapManager);
		mapView = (MapView) findViewById(R.id.mapView);
		mapView.setBuiltInZoomControls(true);
		mapView.setDrawOverlayWhenZooming(true);

		// 添加定位图层
		mLocationOverlay = new MyLocationOverlay(this, mapView);
		mapView.getOverlays().add(mLocationOverlay);
		getOverlay = new GetOverlay();
		mapView.getOverlays().add(getOverlay);

		gotoLocate();

		Button buttonGetPos = (Button) findViewById(R.id.buttonGetPos);//获取"我的位置的方法"
		buttonGetPos.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				getInitLoc();
				gotoLocate();
			}
		});

		editCity = (EditText) findViewById(R.id.editTextCity);
		editGeoCodeKey = (EditText) findViewById(R.id.editTextAera);
		Button buttonSearchCity = (Button) findViewById(R.id.buttonSearchCity);
		buttonSearchCity.setOnClickListener(new View.OnClickListener() {//点击按钮定位需要去的地方

			@Override
			public void onClick(View v) {

				mSearch.geocode(editGeoCodeKey.getText().toString(), editCity
						.getText().toString());
				// mapView.getOverlays().add(getOverlay);

			}
		});
		areaText = (EditText) findViewById(R.id.searchKeywords);
		Button buttonSearchArea = (Button) findViewById(R.id.buttonSearchArea);
		buttonSearchArea.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				
				mSearch.poiSearchNearBy(areaText.getText().toString(),// 搜索XX附近5000米范围的XXX
						geoPoint, 5000);

			}
		});

		// 注册定位事件
		mLocationListener = new LocationListener() {
			public void onLocationChanged(Location location) {
				if (location != null) {
					Log.i(TAG, "" + location.getLatitude());
					Log.i(TAG, "" + location.getLongitude());
					geoPoint = new GeoPoint(
							(int) (location.getLatitude() * 1e6),
							(int) (location.getLongitude() * 1e6));
					gotoLocate();
				}
			}

		};

		mSearch = new MKSearch();//搜索服务类
		mSearch.init(mapManager, new MKSearchListener() {
			public void onGetAddrResult(MKAddrInfo res, int error) {
				if (error != 0) {
					String str = String.format("错误号:%d", error);
					Toast.makeText(LBSProjectActivity.this, str,
							Toast.LENGTH_LONG).show();
					return;
				}

				mapView.getController().animateTo(res.geoPt);

//				String strInfo = String.format("纬度:%f 经度:%f\r\n",
//						res.geoPt.getLatitudeE6() / 1e6,
//						res.geoPt.getLongitudeE6() / 1e6);

				geoPoint = res.geoPt;

				// Toast.makeText(LBSProjectActivity.this, strInfo,
				// Toast.LENGTH_LONG).show();
				Drawable marker = getResources().getDrawable(
						R.drawable.iconmarka); // 得到需要标在地图上的资源
				marker.setBounds(0, 0, marker.getIntrinsicWidth(),
						marker.getIntrinsicHeight()); // 为maker定义位置和边界
				mapView.getOverlays().clear();
				mapView.getOverlays().add(getOverlay);
				mapView.getOverlays().add(
						new OverItemT(marker, LBSProjectActivity.this,
								res.geoPt, res.strAddr));
			}

			public void onGetPoiResult(MKPoiResult res, int type, int error) {
				if (res == null) {
					Log.d("onGetPoiResult", "the onGetPoiResult res is " + type
							+ "__" + error);
				} else
					Log.d("onGetPoiResult",
							"the onGetPoiResult res is "
									+ res.getCurrentNumPois() + "__"
									+ res.getNumPages() + "__"
									+ res.getNumPois() + "__" + type + "__"
									+ error);

				// 错误号可参考MKEvent中的定义
				if (error != 0 || res == null) {
					Log.d("onGetPoiResult", "the onGetPoiResult res 0 ");
					Toast.makeText(LBSProjectActivity.this, "抱歉,未找到结果",
							Toast.LENGTH_LONG).show();
					return;
				}

				ArrayList<MKPoiResult> poiResult = res.getMultiPoiResult();
				if (poiResult != null)
					Log.d("onGetPoiResult", "the onGetPoiResult res 1__"
							+ poiResult.size());
				// 将地图移动到第一个POI中心点
				if (res.getCurrentNumPois() > 0) {
					Log.d("onGetPoiResult", "the onGetPoiResult res 2");
					// 将poi结果显示到地图上
					PoiOverlay poiOverlay = new PoiOverlay(
							LBSProjectActivity.this, mapView);
					poiOverlay.setData(res.getAllPoi());
					mapView.getOverlays().clear();
					mapView.getOverlays().add(getOverlay);
					mapView.getOverlays().add(poiOverlay);
					mapView.invalidate();
					mapView.getController().animateTo(res.getPoi(0).pt);
				} else if (res.getCityListNum() > 0) {
					Log.d("onGetPoiResult", "the onGetPoiResult res 3");
					String strInfo = "在";
					for (int i = 0; i < res.getCityListNum(); i++) {
						strInfo += res.getCityListInfo(i).city;
						strInfo += ",";
					}
					strInfo += "找到结果";
					Toast.makeText(LBSProjectActivity.this, strInfo,
							Toast.LENGTH_LONG).show();
				}

				Log.d("onGetPoiResult", "the onGetPoiResult res 4");

			}

			public void onGetDrivingRouteResult(MKDrivingRouteResult res,
					int error) {
			}

			public void onGetTransitRouteResult(MKTransitRouteResult res,
					int error) {
			}

			public void onGetWalkingRouteResult(MKWalkingRouteResult res,
					int error) {
			}

		});

	}

	private void gotoLocate() {// 获取所在位置
		Drawable marker = getResources().getDrawable(R.drawable.iconmarka); // 得到需要标在地图上的资源
		marker.setBounds(0, 0, marker.getIntrinsicWidth(),
				marker.getIntrinsicHeight()); // 为maker定义位置和边界
		mapView.getOverlays().clear();
		mapView.getOverlays().add(getOverlay);
		mapView.getOverlays().add(
				new OverItemT(marker, LBSProjectActivity.this, geoPoint, ""));

		mapView.getController().animateTo(geoPoint);
		mapController = mapView.getController();
		// 设置地图的中心
		mapController.setCenter(geoPoint);
		// 设置地图默认的缩放级别
		mapController.setZoom(16);
	}

	private void getInitLoc() {// 初始化时候获取坐标
		try {

			LocationManager locationManager;
			String context = Context.LOCATION_SERVICE;
			locationManager = (LocationManager) getSystemService(context);
			// String provider = LocationManager.GPS_PROVIDER;

			Criteria criteria = new Criteria();
			criteria.setAccuracy(Criteria.ACCURACY_FINE);
			criteria.setAltitudeRequired(false);
			criteria.setBearingRequired(false);
			criteria.setCostAllowed(true);
			criteria.setPowerRequirement(Criteria.POWER_LOW);
			String provider = locationManager.getBestProvider(criteria, true);
			Location location = locationManager.getLastKnownLocation(provider);
			geoPoint = new GeoPoint((int) (location.getLatitude() * 1e6),
					(int) (location.getLongitude() * 1e6));
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@Override
	protected void onDestroy() {
		if (mapManager != null) {
			// 程序退出前需调用此方法
			mapManager.destroy();
			mapManager = null;
		}
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		if (mapManager != null) {
			// 终止百度地图API
			mapManager.getLocationManager().removeUpdates(mLocationListener);
			mLocationOverlay.disableMyLocation();
			mLocationOverlay.disableCompass(); // 关闭指南针
			mapManager.stop();
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		if (mapManager != null) {
			// 开启百度地图API
			// 注册定位事件,定位后将地图移动到定位点
			mapManager.getLocationManager().requestLocationUpdates(
					mLocationListener);
			mLocationOverlay.enableMyLocation();
			mLocationOverlay.enableCompass(); // 打开指南针
			mapManager.start();
		}
		super.onResume();
	}

	/**
	 * * 实现MKSearchListener接口,用于实现异步搜索服务 * @author liufeng
	 */
	public class MySearchListener implements MKSearchListener {
		
		public void onGetAddrResult(MKAddrInfo result, int iError) {
		}

		public void onGetDrivingRouteResult(MKDrivingRouteResult result,
				int iError) {
		}

		/**
		 * * POI搜索结果(范围检索、城市POI检索、周边检索) * * @param result 搜索结果 * @param type
		 * 返回结果类型(11,12,21:poi列表 7:城市列表) * @param iError 错误号(0表示正确返回)
		 */
		@Override
		public void onGetPoiResult(MKPoiResult result, int type, int iError) {
			if (result == null) {
				return;
			}
			// PoiOverlay是baidu map api提供的用于显示POI的Overlay
			PoiOverlay poioverlay = new PoiOverlay(LBSProjectActivity.this,
					mapView);
			// 设置搜索到的POI数据
			poioverlay.setData(result.getAllPoi());
			// 在地图上显示PoiOverlay(将搜索到的兴趣点标注在地图上)
			mapView.getOverlays().add(poioverlay);
		}

	
		public void onGetTransitRouteResult(MKTransitRouteResult result,
				int iError) {
		}

		
		public void onGetWalkingRouteResult(MKWalkingRouteResult result,
				int iError) {
		}
	}

	class GetOverlay extends Overlay {
		GeoPoint geo;

		@Override
		public void draw(Canvas canvas, MapView gmapView, boolean arg2) {
			super.draw(canvas, mapView, arg2);
			if (geo == null) {
				return;
			}
			Log.i("11111111111111111111", arg2 + "-------draw--");
		}

		@Override
		public boolean onTap(GeoPoint geo, MapView arg1) {
			geoPoint = geo;
			Drawable marker = getResources().getDrawable(R.drawable.iconmarka); // 得到需要标在地图上的资源
			marker.setBounds(0, 0, marker.getIntrinsicWidth(),
					marker.getIntrinsicHeight()); // 为maker定义位置和边界
			mapView.getOverlays().clear();
			mapView.getOverlays().add(getOverlay);
			mapView.getOverlays()
					.add(new OverItemT(marker, LBSProjectActivity.this,
							geoPoint, ""));
			Log.i("11111111111111111111", geo.getLongitudeE6() / 1E6
					+ "----------" + geo.getLatitudeE6() / 1E6);
			return super.onTap(geo, arg1);
		}

	}

	private static final int TOOLBAR0 = 0;
	private static final int TOOLBAR1 = 1;
	private static final int TOOLBAR2 = 2;
	private static final int TOOLBAR3 = 3;

	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, TOOLBAR0, 1, "KTV").setIcon(
				android.R.drawable.ic_btn_speak_now);
		menu.add(0, TOOLBAR1, 2, "学校").setIcon(
				android.R.drawable.ic_menu_myplaces);
		menu.add(0, TOOLBAR2, 3, "餐厅").setIcon(
				android.R.drawable.ic_menu_my_calendar);
		menu.add(0, TOOLBAR3, 4, "公园").setIcon(
				android.R.drawable.ic_menu_gallery);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			mSearch.poiSearchNearBy("KTV", geoPoint, 5000);//搜索ktv
			break;
		case 1:
			mSearch.poiSearchNearBy("学校", geoPoint, 5000);//.搜索学校
			break;
		case 2:
			mSearch.poiSearchNearBy("餐厅", geoPoint, 5000);//搜索餐厅
			break;
		case 3:
			mSearch.poiSearchNearBy("公园", geoPoint, 5000);//搜索公园
			break;
		}

		return super.onOptionsItemSelected(item);
	}

}
原文地址:https://www.cnblogs.com/xiashenbin/p/2668513.html