1. 程式人生 > >高德地圖精確查詢與定位RegeocodeQuery與GeocodeQuery

高德地圖精確查詢與定位RegeocodeQuery與GeocodeQuery

根據輸入的字串精確查詢位置,用GeocodeQuery查詢座標,然後根據獲取到的座標,用RegeocodeQuery查詢地址。例子中用了兩個頁面,一個是顯示地址資訊及定位的頁面,另一個是搜尋頁面,點選搜尋結果返回顯示頁面,顯示資訊並定位:

顯示並定位的頁面:


public class SaleMapActivity extends AppCompatActivity implements GeocodeSearch.OnGeocodeSearchListener {
    private static final String TAG = "SaleMapActivity";

    @BindView
(R.id.iv_mapBack) ImageView ivMapBack; @BindView(R.id.afterSaleMap) MapView afterSaleMap; @BindView(R.id.iv_saleSear) ImageView ivSaleSear; @BindView(R.id.rl_sale_search) RelativeLayout rlSaleSearch; @BindView(R.id.tv_pointName) TextView tvPointName; @BindView
(R.id.tv_distance) TextView tvDistance; @BindView(R.id.iv_location) ImageView ivLocation; @BindView(R.id.tv_location) TextView tvLocation; @BindView(R.id.ll_location) LinearLayout llLocation; @BindView(R.id.iv_phone) ImageView ivPhone; @BindView(R.id.tv_phone) TextView tvPhone
; @BindView(R.id.ll_phone) LinearLayout llPhone; @BindView(R.id.map_bottom) LinearLayout mapBottom; AMap aMap; //宣告mLocationOption物件 public AMapLocationClientOption mLocationOption = null; //宣告AMapLocationClient類物件 public AMapLocationClient mLocationClient = null; private Marker geoMarker; private Marker regeoMarker; private Double lat; private Double lon; private String mCity = ""; private String areaInfo=""; private String adCode = ""; Context mContext; private GeocodeSearch geocoderSearch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sale_map); ButterKnife.bind(this); afterSaleMap.onCreate(savedInstanceState); mContext = SaleMapActivity.this; //初始化定位 mLocationClient = new AMapLocationClient(getApplicationContext()); //設定定位回撥監聽 mLocationClient.setLocationListener(mLocationListener); initAmap(); } /** * * 初始化AMap物件 */ private void initAmap() { if (aMap == null) { aMap = afterSaleMap.getMap(); } setUpMap(); geocoderSearch = new GeocodeSearch(mContext); geocoderSearch.setOnGeocodeSearchListener(this); } private void setUpMap() { //初始化定位引數 mLocationOption = new AMapLocationClientOption(); //設定定位模式為高精度模式,Battery_Saving為低功耗模式,Device_Sensors是僅裝置模式 mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy); //設定是否返回地址資訊(預設返回地址資訊) mLocationOption.setNeedAddress(true); //設定是否只定位一次,預設為false mLocationOption.setOnceLocation(true); //設定是否強制重新整理WIFI,預設為強制重新整理 mLocationOption.setWifiActiveScan(true); //設定是否允許模擬位置,預設為false,不允許模擬位置 mLocationOption.setMockEnable(false); //設定定位間隔,單位毫秒,預設為2000ms // mLocationOption.setInterval(2000); //給定位客戶端物件設定定位引數 mLocationClient.setLocationOption(mLocationOption); //啟動定位 mLocationClient.startLocation(); //重新定位時移除紅氣泡,再重新初始化 geoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f) .icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_BLUE))); // geoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f) // .icon(BitmapDescriptorFactory.fromResource(R.drawable.cur_position))); // regeoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f) // .icon(BitmapDescriptorFactory // .defaultMarker(BitmapDescriptorFactory.HUE_RED))); regeoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f) .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_map_search))); } //宣告定位回撥監聽器 public AMapLocationListener mLocationListener = new AMapLocationListener() { @Override public void onLocationChanged(AMapLocation amapLocation) { if (amapLocation != null) { if (amapLocation.getErrorCode() == 0) { //定位成功回撥資訊,設定相關訊息 amapLocation.getLocationType();//獲取當前定位結果來源,如網路定位結果,詳見定位型別表 amapLocation.getLatitude();//獲取緯度 amapLocation.getLongitude();//獲取經度 amapLocation.getAccuracy();//獲取精度資訊 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(amapLocation.getTime()); df.format(date);//定位時間 amapLocation.getAddress();//地址,如果option中設定isNeedAddress為false,則沒有此結果,網路定位結果中會有地址資訊,GPS定位不返回地址資訊。 amapLocation.getCountry();//國家資訊 amapLocation.getProvince();//省資訊 mCity = amapLocation.getCity();//城市資訊 amapLocation.getDistrict();//城區資訊 amapLocation.getStreet();//街道資訊 amapLocation.getStreetNum();//街道門牌號資訊 amapLocation.getCityCode();//城市編碼 adCode = amapLocation.getAdCode();//地區編碼 amapLocation.getAoiName();//獲取當前定位點的AOI資訊 lat = amapLocation.getLatitude(); lon = amapLocation.getLongitude(); areaInfo = amapLocation.getProvince()+" "+amapLocation.getCity() +" "+amapLocation.getDistrict(); Log.v("pcw", "lat : " + lat + " lon : " + lon+" adCode: "+adCode+","+areaInfo); Log.v("pcw", "amapLocation="+amapLocation.toString()); // etEAddr.setText(amapLocation.getAoiName()); tvPointName.setText(amapLocation.getAoiName()); tvLocation.setText(amapLocation.getAddress()); // 設定當前地圖顯示為當前位置 aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 16)); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(new LatLng(lat, lon)); markerOptions.title("當前位置"); markerOptions.visible(true); // BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.location_marker)); // BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.cur_position); //設定當前位置的marker圖示 ImageView imageView = new ImageView(SaleMapActivity.this); imageView.setImageResource(R.drawable.cur_position); BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromView(imageView); markerOptions.icon(bitmapDescriptor); aMap.addMarker(markerOptions); // mLocationListener.onLocationChanged(amapLocation); } else { //顯示錯誤資訊ErrCode是錯誤碼,errInfo是錯誤資訊,詳見錯誤碼錶。 Log.e("AmapError", "location Error, ErrCode:" + amapLocation.getErrorCode() + ", errInfo:" + amapLocation.getErrorInfo()); Toast.makeText(mContext,amapLocation.getErrorInfo(),Toast.LENGTH_LONG).show(); } } } }; @Override protected void onActivityResult(int requestCode,int resultCode,Intent data){ LogUtil.d("SaleMapActivity","sdjflksdfjdlskf"); if(requestCode == 1){ if(resultCode == RESULT_OK){ LogUtil.d("SaleMapActivity","onActivityResult==========="); Bundle bundle = data.getBundleExtra("searAddr"); GeocodeAddress address = bundle.getParcelable("addr"); //根據傳回來的地址座標獲取該地點的位置詳細資訊 //通過 RegeocodeQuery(LatLonPoint point, float radius, java.lang.String latLonType) 設定查詢引數 RegeocodeQuery rQuery = new RegeocodeQuery(address.getLatLonPoint(),200,GeocodeSearch.AMAP); //呼叫 GeocodeSearch 的 getFromLocationAsyn(RegeocodeQuery regeocodeQuery) 方法發起請求。 //通過回撥介面 onRegeocodeSearched 解析返回的結果 geocoderSearch.getFromLocationAsyn(rQuery); } } } @OnClick({R.id.iv_mapBack, R.id.rl_sale_search, R.id.ll_phone}) public void onClick(View view) { switch (view.getId()) { case R.id.iv_mapBack: finish(); break; case R.id.rl_sale_search: Intent searchIntent = new Intent(SaleMapActivity.this, SearchSaleActivity.class); startActivityForResult(searchIntent,1); // startActivity(searchIntent); break; case R.id.ll_phone: break; } } @Override public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) { if(i== 1000){ if(regeocodeResult != null && regeocodeResult.getRegeocodeAddress()!= null && regeocodeResult.getRegeocodeAddress().getFormatAddress() != null){ adCode = regeocodeResult.getRegeocodeAddress().getAdCode(); LatLng latLng= convertToLatLng(regeocodeResult.getRegeocodeQuery().getPoint()); aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15)); regeoMarker.setPosition(latLng); RegeocodeAddress address = regeocodeResult.getRegeocodeAddress(); List<PoiItem> poiItems = address.getPois(); for(int j = 0;j<poiItems.size();j++){ PoiItem item = poiItems.get(j); LogUtil.d(TAG,"Title="+item.getTitle()+",Distance="+item.getDistance()+",AdName="+item.getAdName()+",Tel"+item.getTel() +",BusinessArea="+item.getBusinessArea()+",Snippet="+item.getSnippet()+",Direction"+item.getDirection() +",TypeDes"+item.getTypeDes()); } tvPointName.setText(poiItems.get(0).getTitle()+"附近"); //我的當前位置與搜尋到的位置的距離 LatLng latLng1 = new LatLng(lat,lon); float distance = AMapUtils.calculateLineDistance(latLng1,regeoMarker.getPosition()); tvDistance.setText(String.valueOf(distance)); tvLocation.setText(address.getFormatAddress()); tvPhone.setText(poiItems.get(0).getTel()); Toast.makeText(mContext, "定位成功", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(mContext, "定位失敗", Toast.LENGTH_LONG).show(); } }else{ Toast.makeText(mContext, i, Toast.LENGTH_LONG).show(); } } public LatLng convertToLatLng(LatLonPoint point){ return new LatLng(point.getLatitude(),point.getLongitude()); } @Override public void onGeocodeSearched(GeocodeResult geocodeResult, int i) { } }
2. 搜尋頁面:
public class SearchSaleActivity extends AppCompatActivity {
    private static final String TAG = "SearchSaleActivity";

    @BindView(R.id.salesearch_edit)
    TextField salesearchEdit;
    @BindView(R.id.tv_saleCancel)
    TextView tvSaleCancel;
    @BindView(R.id.lvResult)
    ListView lvResult;
    GeocodeSearch geocodeSearch;
    Context mContext;
    SearchMapAdapter adapter;
    List<GeocodeAddress> addrList;

    @Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_sale);
        ButterKnife.bind(this);
        mContext = SearchSaleActivity.this;
        addrList = new ArrayList<GeocodeAddress>();
        //構造 GeocodeSearch 物件,並設定監聽。
geocodeSearch = new GeocodeSearch(mContext);
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

            }

            @Override
public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
                //地理編碼;根據地址獲取座標
if(i == 1000){
                    LogUtil.d(TAG,"success");
                    if(geocodeResult != null && geocodeResult.getGeocodeAddressList() != null
&& geocodeResult.getGeocodeAddressList().size() != 0){
                        LogUtil.d(TAG,""+geocodeResult.getGeocodeQuery().getLocationName());
                        addrList = geocodeResult.getGeocodeAddressList();
                        adapter = new SearchMapAdapter(mContext,addrList);
                        lvResult.setAdapter(adapter);

                    }
                }
            }
        });
        salesearchEdit.addTextChangedListener(new MyTextChangeListener());
        lvResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext,SaleMapActivity.class);
                Bundle bundle = new Bundle();
                bundle.putParcelable("addr",addrList.get(position));
                intent.putExtra("searAddr",bundle);
                setResult(RESULT_OK,intent);
                finish();
            }
        });
    }

    //文字框的改變監聽
class MyTextChangeListener implements 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) {
            String newText = s.toString().trim();
            if(newText != null && !newText.equals("")){
                //通過 GeocodeQuery(java.lang.String locationName, java.lang.String city) 設定查詢引數
                //name表示地址,第二個引數表示查詢城市,中文或者中文全拼,citycode、adcode
GeocodeQuery query = new GeocodeQuery(newText,"0532");
                //呼叫 GeocodeSearch 的 getFromLocationNameAsyn(GeocodeQuery geocodeQuery) 方法發起請求。
                //通過回撥介面 onGeocodeSearched 解析返回的結果
geocodeSearch.getFromLocationNameAsyn(query);
            }

        }

        @Override
public void afterTextChanged(Editable s) {

        }
    }

    @OnClick(R.id.tv_saleCancel)
    public void onClick() {
    }
}