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

来源:互联网 发布:淘宝优惠券 平台 搭建 编辑:程序博客网 时间:2024/04/30 21:50


    
001package com.lbsproject;
002 
003import java.util.ArrayList;
004 
005import android.content.Context;
006import android.graphics.Canvas;
007import android.graphics.Color;
008import android.graphics.Paint;
009import android.graphics.Point;
010import android.graphics.drawable.Drawable;
011import android.location.Criteria;
012import android.location.Location;
013import android.location.LocationManager;
014import android.os.Bundle;
015import android.util.Log;
016import android.view.Menu;
017import android.view.MenuItem;
018import android.view.MotionEvent;
019import android.view.View;
020import android.widget.Button;
021import android.widget.EditText;
022import android.widget.Toast;
023 
024import com.baidu.mapapi.BMapManager;
025import com.baidu.mapapi.GeoPoint;
026import com.baidu.mapapi.LocationListener;
027import com.baidu.mapapi.MKAddrInfo;
028import com.baidu.mapapi.MKDrivingRouteResult;
029import com.baidu.mapapi.MKPoiResult;
030import com.baidu.mapapi.MKSearch;
031import com.baidu.mapapi.MKSearchListener;
032import com.baidu.mapapi.MKTransitRouteResult;
033import com.baidu.mapapi.MKWalkingRouteResult;
034import com.baidu.mapapi.MapActivity;
035import com.baidu.mapapi.MapController;
036import com.baidu.mapapi.MapView;
037import com.baidu.mapapi.MyLocationOverlay;
038import com.baidu.mapapi.Overlay;
039import com.baidu.mapapi.PoiOverlay;
040import com.baidu.mapapi.Projection;
041import com.lbsproject.LBSProjectActivity.GetOverlay;
042 
043public classLBSProjectActivityextendsMapActivity {
044    protectedstaticfinal String TAG = null;
045    privateBMapManager mapManager;
046    privateMapView mapView;
047    privateMapController mapController;
048    privateMKSearch mSearch =null;
049    privateGeoPoint geoPoint =new GeoPoint(122084095,37422006);;
050    LocationListener mLocationListener =null;
051    MyLocationOverlay mLocationOverlay =null;
052    privateEditText editCity;
053    privateEditText editGeoCodeKey;
054    privateEditText areaText;
055    privateGetOverlay getOverlay;
056 
057    @Override
058    publicvoidonCreate(Bundle savedInstanceState) {
059        super.onCreate(savedInstanceState);
060        setContentView(R.layout.main);
061     
062        getInitLoc();// 程序打开时候获取当前位置 显示地图上
063        mapManager =newBMapManager(getApplication());
064 
065        // init方法的第一个参数需填入申请的APIKey
066        mapManager.init("2150650BE0DCF874994B845CEC7B60A0518E6AFE",null);
067        super.initMapActivity(mapManager);
068        mapView = (MapView) findViewById(R.id.mapView);
069        mapView.setBuiltInZoomControls(true);
070        mapView.setDrawOverlayWhenZooming(true);
071 
072        // 添加定位图层
073        mLocationOverlay =newMyLocationOverlay(this, mapView);
074        mapView.getOverlays().add(mLocationOverlay);
075        getOverlay =newGetOverlay();
076        mapView.getOverlays().add(getOverlay);
077 
078        gotoLocate();
079 
080        Button buttonGetPos = (Button) findViewById(R.id.buttonGetPos);//获取"我的位置的方法"
081        buttonGetPos.setOnClickListener(newView.OnClickListener() {
082 
083            publicvoidonClick(View v) {
084                getInitLoc();
085                gotoLocate();
086            }
087        });
088 
089        editCity = (EditText) findViewById(R.id.editTextCity);
090        editGeoCodeKey = (EditText) findViewById(R.id.editTextAera);
091        Button buttonSearchCity = (Button) findViewById(R.id.buttonSearchCity);
092        buttonSearchCity.setOnClickListener(newView.OnClickListener() {//点击按钮定位需要去的地方
093 
094            @Override
095            publicvoidonClick(View v) {
096 
097                mSearch.geocode(editGeoCodeKey.getText().toString(), editCity
098                        .getText().toString());
099                // mapView.getOverlays().add(getOverlay);
100 
101            }
102        });
103        areaText = (EditText) findViewById(R.id.searchKeywords);
104        Button buttonSearchArea = (Button) findViewById(R.id.buttonSearchArea);
105        buttonSearchArea.setOnClickListener(newView.OnClickListener() {
106 
107            @Override
108            publicvoidonClick(View v) {
109 
110                 
111                mSearch.poiSearchNearBy(areaText.getText().toString(),// 搜索XX附近5000米范围的XXX
112                        geoPoint,5000);
113 
114            }
115        });
116 
117        // 注册定位事件
118        mLocationListener =newLocationListener() {
119            publicvoidonLocationChanged(Location location) {
120                if(location !=null) {
121                    Log.i(TAG,""+ location.getLatitude());
122                    Log.i(TAG,""+ location.getLongitude());
123                    geoPoint =newGeoPoint(
124                            (int) (location.getLatitude() * 1e6),
125                            (int) (location.getLongitude() * 1e6));
126                    gotoLocate();
127                }
128            }
129 
130        };
131 
132        mSearch =newMKSearch();//搜索服务类
133        mSearch.init(mapManager,newMKSearchListener() {
134            publicvoidonGetAddrResult(MKAddrInfo res,interror) {
135                if(error !=0) {
136                    String str = String.format("错误号:%d", error);
137                    Toast.makeText(LBSProjectActivity.this, str,
138                            Toast.LENGTH_LONG).show();
139                    return;
140                }
141 
142                mapView.getController().animateTo(res.geoPt);
143 
144//              String strInfo = String.format("纬度:%f 经度:%f\r\n",
145//                      res.geoPt.getLatitudeE6() / 1e6,
146//                      res.geoPt.getLongitudeE6() / 1e6);
147 
148                geoPoint = res.geoPt;
149 
150                // Toast.makeText(LBSProjectActivity.this, strInfo,
151                // Toast.LENGTH_LONG).show();
152                Drawable marker = getResources().getDrawable(
153                        R.drawable.iconmarka);// 得到需要标在地图上的资源
154                marker.setBounds(0,0, marker.getIntrinsicWidth(),
155                        marker.getIntrinsicHeight());// 为maker定义位置和边界
156                mapView.getOverlays().clear();
157                mapView.getOverlays().add(getOverlay);
158                mapView.getOverlays().add(
159                        newOverItemT(marker, LBSProjectActivity.this,
160                                res.geoPt, res.strAddr));
161            }
162 
163            publicvoidonGetPoiResult(MKPoiResult res,inttype, interror) {
164                if(res ==null) {
165                    Log.d("onGetPoiResult","the onGetPoiResult res is "+ type
166                            +"__"+ error);
167                }else
168                    Log.d("onGetPoiResult",
169                            "the onGetPoiResult res is "
170                                    + res.getCurrentNumPois() +"__"
171                                    + res.getNumPages() +"__"
172                                    + res.getNumPois() +"__"+ type + "__"
173                                    + error);
174 
175                // 错误号可参考MKEvent中的定义
176                if(error !=0 || res == null) {
177                    Log.d("onGetPoiResult","the onGetPoiResult res 0 ");
178                    Toast.makeText(LBSProjectActivity.this,"抱歉,未找到结果",
179                            Toast.LENGTH_LONG).show();
180                    return;
181                }
182 
183                ArrayList<MKPoiResult> poiResult = res.getMultiPoiResult();
184                if(poiResult !=null)
185                    Log.d("onGetPoiResult","the onGetPoiResult res 1__"
186                            + poiResult.size());
187                // 将地图移动到第一个POI中心点
188                if(res.getCurrentNumPois() >0) {
189                    Log.d("onGetPoiResult","the onGetPoiResult res 2");
190                    // 将poi结果显示到地图上
191                    PoiOverlay poiOverlay =newPoiOverlay(
192                            LBSProjectActivity.this, mapView);
193                    poiOverlay.setData(res.getAllPoi());
194                    mapView.getOverlays().clear();
195                    mapView.getOverlays().add(getOverlay);
196                    mapView.getOverlays().add(poiOverlay);
197                    mapView.invalidate();
198                    mapView.getController().animateTo(res.getPoi(0).pt);
199                }elseif (res.getCityListNum() > 0) {
200                    Log.d("onGetPoiResult","the onGetPoiResult res 3");
201                    String strInfo ="在";
202                    for(inti = 0; i < res.getCityListNum(); i++) {
203                        strInfo += res.getCityListInfo(i).city;
204                        strInfo +=",";
205                    }
206                    strInfo +="找到结果";
207                    Toast.makeText(LBSProjectActivity.this, strInfo,
208                            Toast.LENGTH_LONG).show();
209                }
210 
211                Log.d("onGetPoiResult","the onGetPoiResult res 4");
212 
213            }
214 
215            publicvoidonGetDrivingRouteResult(MKDrivingRouteResult res,
216                    interror) {
217            }
218 
219            publicvoidonGetTransitRouteResult(MKTransitRouteResult res,
220                    interror) {
221            }
222 
223            publicvoidonGetWalkingRouteResult(MKWalkingRouteResult res,
224                    interror) {
225            }
226 
227        });
228 
229    }
230 
231    privatevoidgotoLocate() {// 获取所在位置
232        Drawable marker = getResources().getDrawable(R.drawable.iconmarka);// 得到需要标在地图上的资源
233        marker.setBounds(0,0, marker.getIntrinsicWidth(),
234                marker.getIntrinsicHeight());// 为maker定义位置和边界
235        mapView.getOverlays().clear();
236        mapView.getOverlays().add(getOverlay);
237        mapView.getOverlays().add(
238                newOverItemT(marker, LBSProjectActivity.this, geoPoint,""));
239 
240        mapView.getController().animateTo(geoPoint);
241        mapController = mapView.getController();
242        // 设置地图的中心
243        mapController.setCenter(geoPoint);
244        // 设置地图默认的缩放级别
245        mapController.setZoom(16);
246    }
247 
248    privatevoidgetInitLoc() {// 初始化时候获取坐标
249        try{
250 
251            LocationManager locationManager;
252            String context = Context.LOCATION_SERVICE;
253            locationManager = (LocationManager) getSystemService(context);
254            // String provider = LocationManager.GPS_PROVIDER;
255 
256            Criteria criteria =newCriteria();
257            criteria.setAccuracy(Criteria.ACCURACY_FINE);
258            criteria.setAltitudeRequired(false);
259            criteria.setBearingRequired(false);
260            criteria.setCostAllowed(true);
261            criteria.setPowerRequirement(Criteria.POWER_LOW);
262            String provider = locationManager.getBestProvider(criteria,true);
263            Location location = locationManager.getLastKnownLocation(provider);
264            geoPoint =newGeoPoint((int) (location.getLatitude() * 1e6),
265                    (int) (location.getLongitude() * 1e6));
266        } catch (Exception e) {
267            // TODO: handle exception
268        }
269    }
270 
271    @Override
272    protectedbooleanisRouteDisplayed() {
273        returnfalse;
274    }
275 
276    @Override
277    protectedvoidonDestroy() {
278        if(mapManager !=null) {
279            // 程序退出前需调用此方法
280            mapManager.destroy();
281            mapManager =null;
282        }
283        super.onDestroy();
284    }
285 
286    @Override
287    protectedvoidonPause() {
288        if(mapManager !=null) {
289            // 终止百度地图API
290            mapManager.getLocationManager().removeUpdates(mLocationListener);
291            mLocationOverlay.disableMyLocation();
292            mLocationOverlay.disableCompass();// 关闭指南针
293            mapManager.stop();
294        }
295        super.onPause();
296    }
297 
298    @Override
299    protectedvoidonResume() {
300        if(mapManager !=null) {
301            // 开启百度地图API
302            // 注册定位事件,定位后将地图移动到定位点
303            mapManager.getLocationManager().requestLocationUpdates(
304                    mLocationListener);
305            mLocationOverlay.enableMyLocation();
306            mLocationOverlay.enableCompass();// 打开指南针
307            mapManager.start();
308        }
309        super.onResume();
310    }
311 
312    /**
313     * * 实现MKSearchListener接口,用于实现异步搜索服务 * @author liufeng
314     */
315    publicclassMySearchListener implementsMKSearchListener {
316         
317        publicvoidonGetAddrResult(MKAddrInfo result,intiError) {
318        }
319 
320        publicvoidonGetDrivingRouteResult(MKDrivingRouteResult result,
321                intiError) {
322        }
323 
324        /**
325         * * POI搜索结果(范围检索、城市POI检索、周边检索) * * @param result 搜索结果 * @param type
326         * 返回结果类型(11,12,21:poi列表 7:城市列表) * @param iError 错误号(0表示正确返回)
327         */
328        @Override
329        publicvoidonGetPoiResult(MKPoiResult result,inttype, intiError) {
330            if(result ==null) {
331                return;
332            }
333            // PoiOverlay是baidu map api提供的用于显示POI的Overlay
334            PoiOverlay poioverlay =newPoiOverlay(LBSProjectActivity.this,
335                    mapView);
336            // 设置搜索到的POI数据
337            poioverlay.setData(result.getAllPoi());
338            // 在地图上显示PoiOverlay(将搜索到的兴趣点标注在地图上)
339            mapView.getOverlays().add(poioverlay);
340        }
341 
342     
343        publicvoidonGetTransitRouteResult(MKTransitRouteResult result,
344                intiError) {
345        }
346 
347         
348        publicvoidonGetWalkingRouteResult(MKWalkingRouteResult result,
349                intiError) {
350        }
351    }
352 
353    classGetOverlayextends Overlay {
354        GeoPoint geo;
355 
356        @Override
357        publicvoiddraw(Canvas canvas, MapView gmapView,booleanarg2) {
358            super.draw(canvas, mapView, arg2);
359            if(geo ==null) {
360                return;
361            }
362            Log.i("11111111111111111111", arg2 +"-------draw--");
363        }
364 
365        @Override
366        publicbooleanonTap(GeoPoint geo, MapView arg1) {
367            geoPoint = geo;
368            Drawable marker = getResources().getDrawable(R.drawable.iconmarka);// 得到需要标在地图上的资源
369            marker.setBounds(0,0, marker.getIntrinsicWidth(),
370                    marker.getIntrinsicHeight());// 为maker定义位置和边界
371            mapView.getOverlays().clear();
372            mapView.getOverlays().add(getOverlay);
373            mapView.getOverlays()
374                    .add(newOverItemT(marker, LBSProjectActivity.this,
375                            geoPoint,""));
376            Log.i("11111111111111111111", geo.getLongitudeE6() / 1E6
377                    +"----------"+ geo.getLatitudeE6() / 1E6);
378            returnsuper.onTap(geo, arg1);
379        }
380 
381    }
382 
383    privatestaticfinal int TOOLBAR0 = 0;
384    privatestaticfinal int TOOLBAR1 = 1;
385    privatestaticfinal int TOOLBAR2 = 2;
386    privatestaticfinal int TOOLBAR3 = 3;
387 
388    publicbooleanonCreateOptionsMenu(Menu menu) {
389        menu.add(0, TOOLBAR0,1,"KTV").setIcon(
390                android.R.drawable.ic_btn_speak_now);
391        menu.add(0, TOOLBAR1,2,"学校").setIcon(
392                android.R.drawable.ic_menu_myplaces);
393        menu.add(0, TOOLBAR2,3,"餐厅").setIcon(
394                android.R.drawable.ic_menu_my_calendar);
395        menu.add(0, TOOLBAR3,4,"公园").setIcon(
396                android.R.drawable.ic_menu_gallery);
397        returnsuper.onCreateOptionsMenu(menu);
398    }
399 
400    @Override
401    publicbooleanonOptionsItemSelected(MenuItem item) {
402        switch(item.getItemId()) {
403        case0:
404            mSearch.poiSearchNearBy("KTV", geoPoint,5000);//搜索ktv
405            break;
406        case1:
407            mSearch.poiSearchNearBy("学校", geoPoint,5000);//.搜索学校
408            break;
409        case2:
410            mSearch.poiSearchNearBy("餐厅", geoPoint,5000);//搜索餐厅
411            break;
412        case3:
413            mSearch.poiSearchNearBy("公园", geoPoint,5000);//搜索公园
414            break;
415        }
416 
417        returnsuper.onOptionsItemSelected(item);
418    }
419 
420}
原创粉丝点击