Android 바 이 두 맵 위치 지정 후 주변 위치 구현 코드 가 져 오기

본 고 는 안 드 로 이 드 바 이 두 맵 의 포 지 셔 닝 을 설명 한 후 주변 위치의 실현 코드 를 얻 고 여러분 에 게 참고 할 수 있 도록 공유 합 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.
효과 그림:

구체 적 인 코드:
1.레이아웃 파일

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 <RelativeLayout
   android:layout_width="match_parent"
   android:layout_height="@dimen/height_top_bar"
   android:background="@color/common_top_bar_dark"
   android:gravity="center_vertical">

  <Button
    android:id="@+id/btn_location_back"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:drawableLeft="@drawable/back"
    android:text="@string/top_back"
    style="@style/btn_title_bar"
    android:layout_alignParentLeft="true"
    android:onClick="back"
    />

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="@string/location_message"
    style="@style/txt_titlebar_message"/>


  <Button
    android:id="@+id/btn_location_ok"
    android:layout_width="52dp"
    android:layout_height="match_parent"
    android:layout_alignParentRight="true"
    android:background="@drawable/common_tab_bg"
    android:text="@string/txt_queding"
    style="@style/btn_title_bar"/>

 </RelativeLayout>
 <com.baidu.mapapi.map.MapView
   android:layout_weight="2"
   android:id="@+id/mapview_location"
   android:layout_width="fill_parent"
   android:layout_height="match_parent"
   android:clickable="true" />

 <ListView
   android:layout_weight="3"
   android:id="@+id/lv_location_nearby"
   android:layout_width="match_parent"
   android:layout_height="match_parent"/>

</LinearLayout>

레이아웃 파일 은 위 에 바 이 두 맵 의 mapview 이 고 아래 는 주변 위 치 를 표시 하 는 ListView 입 니 다.간단 합 니 다.
1.자동 위치 지정
일단 저희 가 지리 적 위치 에 따라 포 지 셔 닝 을 해 보도 록 하 겠 습 니 다.
1.우선 사용 할 구성 요소 초기 화

 /**
  *      
  */
 private void initView() {
  btnLocationBack = (Button) findViewById(R.id.btn_location_back);
  btnLocationBack.setOnClickListener(this);
  btnLocationOk = (Button) findViewById(R.id.btn_location_ok);
  btnLocationOk.setOnClickListener(this);
  mapViewLocation = (MapView) findViewById(R.id.mapview_location);
  lvLocNear = (ListView) findViewById(R.id.lv_location_nearby);
  nearList = new ArrayList<PoiInfo>();
  adapter = new LocNearAddressAdapter(context, nearList, isSelected);
  lvLocNear.setAdapter(adapter);
 }
2.LocationClient 클래스 를 초기 화 하려 면 주 스 레 드 에서 설명 해 야 합 니 다.

public LocationClient mLocationClient = null;
public BDLocationListener myListener = new MyLocationListener();

public void onCreate() {
 mLocationClient = new LocationClient(getApplicationContext());  //  LocationClient 
 mLocationClient.registerLocationListener( myListener ); //      
}
3.위치 SDK 파라미터 설정
포 지 셔 닝 매개 변 수 를 설정 하 는 것 은 포 지 셔 닝 모드(높 은 정밀도 포 지 셔 닝 모드,낮은 전력 소모 포 지 셔 닝 모드 와 장치 로 만 포 지 셔 닝 모드),좌표 유형 을 되 돌려 주 는 지,GPS 를 열 어 주 는 지,주소 정보,위치 의미 화 정보,POI 정보 등 을 포함한다.
LocationClient Option 클래스,위치 추적 SDK 의 위치 추적 방식 을 설정 하 는 데 사 용 됩 니 다.

private void initLocation(){
  LocationClientOption option = new LocationClientOption();
  option.setLocationMode(LocationMode.Hight_Accuracy
);//  ,     ,      ,   ,   ,   
  option.setCoorType("bd09ll");//  ,  gcj02,            
  int span=1000;
  option.setScanSpan(span);//  ,  0,      ,                 1000ms     
  option.setIsNeedAddress(true);//  ,          ,     
  option.setOpenGps(true);//  ,  false,      gps
  option.setLocationNotify(true);//  ,  false,     gps     1S1     GPS  
  option.setIsNeedLocationDescribe(true);//  ,  false,             ,   BDLocation.getLocationDescribe   ,     “        ”
  option.setIsNeedLocationPoiList(true);//  ,  false,      POI  ,   BDLocation.getPoiList   
option.setIgnoreKillProcess(false);//  ,  false,  SDK     SERVICE,        ,     stop         ,    
  option.SetIgnoreCacheException(false);//  ,  false,      CRASH  ,    
option.setEnableSimulateGps(false);//  ,  false,        gps    ,    
  mLocationClient.setLocOption(option);
 }
4.BDLocationListener 인터페이스 구현

 /**
  *     ,       ,       ,      
  */
 public class MyLocationListenner implements BDLocationListener {
  @Override
  public void onReceiveLocation(BDLocation location) {
   if (location == null) {
    return;
   }
   Log.d("map", "On location change received:" + location);
   Log.d("map", "addr:" + location.getAddrStr());
   if (progressDialog != null) {
    progressDialog.dismiss();
   }

   if (lastLocation != null) {
    if (lastLocation.getLatitude() == location.getLatitude() && lastLocation.getLongitude() == location.getLongitude()) {
     Log.d("map", "same location, skip refresh");
     // mMapView.refresh(); //need this refresh?
     return;
    }
   }
   lastLocation = location;
   mBaiduMap.clear();
   mCurrentLantitude = lastLocation.getLatitude();
   mCurrentLongitude = lastLocation.getLongitude();
   Log.e(">>>>>>>", mCurrentLantitude + "," + mCurrentLongitude);
   LatLng llA = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());
   CoordinateConverter converter = new CoordinateConverter();
   converter.coord(llA);
   converter.from(CoordinateConverter.CoordType.COMMON);
   LatLng convertLatLng = converter.convert();
   OverlayOptions ooA = new MarkerOptions().position(convertLatLng).icon(BitmapDescriptorFactory
     .fromResource(R.drawable.icon_marka))
     .zIndex(4).draggable(true);
   mCurrentMarker = (Marker) mBaiduMap.addOverlay(ooA);
   MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(convertLatLng, 16.0f);
   mBaiduMap.animateMapStatus(u);
   new Thread(new Runnable() {
    @Override
    public void run() {
     searchNeayBy();
    }
   }).start();
  }

  public void onReceivePoi(BDLocation poiLocation) {
   if (poiLocation == null) {
    return;
   }
  }
 }
여기 서 받 아들 인 BDLocation 에는 많은 인자 가 포함 되 어 있 습 니 다.항상 유용 한 것 이 있 을 것 이 라 고 믿 습 니 다.
2.경위도 에 따라 포 지 셔 닝
이런 방법 은 자동 으로 위 치 를 정할 필요 가 없 는데,바로 경위도 에 따라 지도 상의 위 치 를 표시 하 는 것 이다.

 /*
 *         
 * */
 private void showMap(double latitude, double longtitude, String address) {
//  sendButton.setVisibility(View.GONE);
  LatLng llA = new LatLng(latitude, longtitude);
  CoordinateConverter converter = new CoordinateConverter();
  converter.coord(llA);
  converter.from(CoordinateConverter.CoordType.COMMON);
  LatLng convertLatLng = converter.convert();
  OverlayOptions ooA = new MarkerOptions().position(convertLatLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_marka))
    .zIndex(4).draggable(true);
  markerA = (Marker) (mBaiduMap.addOverlay(ooA));
  u = MapStatusUpdateFactory.newLatLngZoom(convertLatLng, 16.0f);
  mBaiduMap.animateMapStatus(u);
  new Thread(new Runnable() {
   @Override
   public void run() {
    searchNeayBy();
   }
  }).start();
 }
3.주변 지리 적 위치 획득
마지막 으로 주변의 지리 적 위 치 를 어떻게 얻 는 지 살 펴 보 겠 습 니 다.여 기 는 SDK 의 한 종류 인 Poi Nearby SearchOption 을 사용 해 야 합 니 다.우 리 는 클래스 참고 사항 을 볼 수 있 습 니 다.
  • PoiNearbySearchOption keyword(java.lang.String key)
  • 검색 키워드
  • PoiNearbySearchOption location(LatLng location)
  • 검색 위치
  • PoiNearbySearchOption pageCapacity(int pageCapacity)
  • 4.567917.페이지 당 용량 을 설정 하고 기본 값 은 페이지 당 10 개 입 니 다.4.567918.
  • PoiNearbySearchOption pageNum(int pageNum)
  • 페이지 번호
  • PoiNearbySearchOption radius(int radius)
  • 검색 의 반경 범 위 를 설정 합 니 다
  • PoiNearbySearchOption sortType(PoiSortType sortType)
  • 검색 결과 정렬 규칙,선택 가능,기본 값
    여 기 는 그것 의 일부 방법 입 니 다.우 리 는 키워드,주변 위치 반경,검색 위치,정렬 규칙,페이지 번호,각 페이지 수량 등 만 설정 해 야 한 다 는 것 을 알 수 있 습 니 다.그리고 우 리 는 OnGetPoiSearch ResultListener 라 는 인 터 페 이 스 를 실현 하여 주변 지리 적 위치 결 과 를 얻 습 니 다.
    
    /**
      *         
      */
     private void searchNeayBy() {
      PoiNearbySearchOption option = new PoiNearbySearchOption();
      option.keyword("   ");
      option.sortType(PoiSortType.distance_from_near_to_far);
      option.location(new LatLng(mCurrentLantitude, mCurrentLongitude));
      if (radius != 0) {
       option.radius(radius);
      } else {
       option.radius(1000);
      }
    
      option.pageCapacity(20);
      mPoiSearch.searchNearby(option);
    
     }
    
    /*
    *           
    * @param poiResult
    */
    
     @Override
     public void onGetPoiResult(PoiResult poiResult) {
      if (poiResult != null) {
       if (poiResult.getAllPoi()!=null&&poiResult.getAllPoi().size()>0){
        nearList.addAll(poiResult.getAllPoi());
        if (nearList != null && nearList.size() > 0) {
         for (int i = 0; i < nearList.size(); i++) {
          isSelected.put(i, false);
         }
        }
        Message msg = new Message();
        msg.what = 0;
        handler.sendMessage(msg);
       }
    
      }
     }
    
    데 이 터 를 가 져 온 후 어댑터 를 업데이트 하여 주변 위 치 를 표시 하면 OK 입 니 다.마지막 으로 작은 기능 을 실현 합 니 다.목록 의 모든 위 치 를 클릭 하고 위 치 를 표시 하 는 작은 아이콘 은 위치 에 따라 달라 집 니 다.
    
     /**
       *             
       */
      lvLocNear.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        adapter.setSelected(i);
        adapter.notifyDataSetChanged();
        PoiInfo ad = (PoiInfo) adapter.getItem(i);
        u = MapStatusUpdateFactory.newLatLng(ad.location);
        mBaiduMap.animateMapStatus(u);
        if (!isLoc) {
         mCurrentMarker.setPosition(ad.location);
        } else {
         markerA.setPosition(ad.location);
        }
       }
      });
    
    자,아주 간단 하고 유용 한 작은 기능 이 사용자 에 게 좋 은 체험 효 과 를 가 져 다 줄 것 입 니 다.
    여러분 들 이 이 문장 을 좋아 하 시 기 를 바 랍 니 다.

    좋은 웹페이지 즐겨찾기