天天看點

高德地圖(基本地圖+定位+周邊搜尋)第一版

package company.com.gaodedemo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMapOptions;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.maps2d.overlay.PoiOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;

import java.util.List;


public class MainActivity extends Activity implements LocationSource,
        AMapLocationListener,AMap.OnMarkerClickListener, AMap.InfoWindowAdapter
        ,AdapterView.OnItemSelectedListener,PoiSearch.OnPoiSearchListener
        ,AMap.OnMapClickListener,AMap.OnInfoWindowClickListener
       ,View.OnClickListener {
    //基本地圖
    private AMap aMap;
    private MapView mapView;
    //定位服務
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private double current_Locationlatitude, current_Locationlongitude;
    private String current_city,current_Adress;
    //POI搜尋
    private ProgressDialog progDialog = null;// 搜尋時進度條
    private Spinner selectDeep;// 選擇城市清單
    private String[] itemDeep = {"酒店", "餐飲", "景區", "影院","中學","酒吧","KTV"};
    private Spinner selectType;// 選擇傳回是否有團購,優惠
    private String[] itemTypes = {"所有poi", "有團購", "有優惠", "有團購或者優惠"};
    private String deepType = "";// poi搜尋類型
    private int searchType = 0;// 搜尋類型
    private int tsearchType = 0;// 目前選擇搜尋類型
    private PoiResult poiResult; // poi傳回的結果
    private int currentPage = 0;// 目前頁面,從0開始計數
    private PoiSearch.Query query;// Poi查詢條件類
    private Marker locationMarker; // 選擇的點
    private PoiSearch poiSearch;
    private PoiOverlay poiOverlay;// poi圖層
    private List<PoiItem> poiItems;// poi資料
    private Marker detailMarker;// 顯示Marker的詳情
    private Button nextButton;// 下一頁
    private GridView gridView;
    private TextView tv_guid;
    private Button locationButton;
    private String Name;
    private LatLonPoint lp_current=new LatLonPoint(39.908127, 116.375257);// 預設西單廣場;
    //選擇地圖顯示模式
    private RadioGroup radioGroup;
    private LinearLayout ll_btn;
    private UiSettings uiSettings;//設定地圖自帶按鈕的位置
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        mapView = (MapView) findViewById(R.id.map_2d);
        mapView.onCreate(savedInstanceState);// 此方法必須重寫
        init();
        SetData();
        AddListener();
    }

    private void AddListener() {
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Name = parent.getAdapter().getItem(position).toString();
                doSearchQuery(Name, deepType, current_city);//POI搜尋的方法

            }
        });
                radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        switch(checkedId){
                            case R.id.map_type_normal_rb:
                                aMap.setMapType(AMap.MAP_TYPE_NORMAL);
                                break;
                            case R.id.map_type_satellite_rb:
                                aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
                                break;
                            case R.id.map_type_night_rb:

                                break;
                        };
                    }
                });
    }
    private void SetData() {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.support_simple_spinner_dropdown_item, itemDeep);
        gridView.setAdapter(adapter);
    }

    /**
     * 初始化AMap對象
     */
    private void init() {

        if (aMap == null) {
            aMap = mapView.getMap();
            uiSettings=aMap.getUiSettings();
            setUpMap();
        }
        locationButton = (Button) findViewById(R.id.Button);
       // locationButton.getBackground().setAlpha(100);
        locationButton.setOnClickListener(this);
        gridView = (GridView) findViewById(R.id.gridView_poi);
        tv_guid = (TextView) findViewById(R.id.Grid_layout);
        aMap.setOnMarkerClickListener(this);// 添加點選marker監聽事件
        aMap.setInfoWindowAdapter(this);// 添加顯示infowindow監聽事件
        //選擇地圖模式
        radioGroup= (RadioGroup) findViewById(R.id.radiogroup);
        ll_btn= (LinearLayout) findViewById(R.id.ll_btn);
        ll_btn.getBackground().setAlpha(150);
    }

    /**
     * 設定一些amap的屬性
     */
    private void setUpMap() {
        // 自定義系統定位小藍點
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.drawable.location_marker));// 設定小藍點的圖示
        myLocationStyle.strokeColor(Color.BLACK);// 設定圓形的邊框顔色
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 設定圓形的填充顔色
        // myLocationStyle.anchor(int,int)//設定小藍點的錨點
        myLocationStyle.strokeWidth(1.0f);// 設定圓形的邊框粗細
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);// 設定定位監聽
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 設定預設定位按鈕是否顯示
        aMap.setMyLocationEnabled(true);// 設定為true表示顯示定位層并可觸發定位,false表示隐藏定位層并不可觸發定位,預設是false
        uiSettings.setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_CENTER);//設定縮放按鈕去位置
        uiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);//設定高德地圖Logo的位置
    }

    /**
     * 方法必須重寫
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必須重寫
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }
    /**
     * 方法必須重寫
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必須重寫
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    /**
     * 定位成功後回調函數
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 顯示系統小藍點
            } else {
                String errText = "定位失敗," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
            current_Locationlatitude = amapLocation.getLatitude();
            current_Locationlongitude = amapLocation.getLongitude();
            current_city = amapLocation.getCity();
            current_Adress=amapLocation.getAddress();
            lp_current=new LatLonPoint(current_Locationlatitude,current_Locationlongitude);
            locationMarker = aMap.addMarker(new MarkerOptions()
                    .anchor(0.5f, 1)
                    .icon(BitmapDescriptorFactory
                            .fromResource(R.drawable.point))
                    .position(new LatLng(lp_current.getLatitude(), lp_current.getLongitude()))
                    .title(current_Adress));
            Log.i("中心位址",current_Adress);
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //設定定位監聽
            mlocationClient.setLocationListener(this);
            //設定為高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //設定定位參數
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法為每隔固定時間會發起一次定位請求,為了減少電量消耗或網絡流量消耗,
            // 注意設定合适的定位時間的間隔(最小間隔支援為2000ms),并且在合适時間調用stopLocation()方法來取消定位請求
            // 在定位結束後,在合适的生命周期調用onDestroy()方法
            // 在單次定位情況下,定位無論成功與否,都無需調用stopLocation()方法移除請求,定位sdk内部會移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    //OnMarkerClickListener未實作的方法
    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }

    //InfoWindowAdapter未實作的方法
    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    //OnItemSelectedListener未實作的方法
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    //OnPoiSearchListener未實作的方法(獲得POI搜尋結果)
    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        if (rCode == 0) {
            if (result != null && result.getQuery() != null) {// 搜尋poi的結果
                if (result.getQuery().equals(query)) {// 是否是同一條
                    poiResult = result;
                    poiItems = poiResult.getPois();// 取得第一頁的poiitem資料,頁數從數字0開始
                    List<SuggestionCity> suggestionCities = poiResult
                            .getSearchSuggestionCitys();// 當搜尋不到poiitem資料時,會傳回含有搜尋關鍵字的城市資訊
                    if (poiItems != null && poiItems.size() > 0) {
                        aMap.clear();// 清理之前的圖示
                        poiOverlay = new PoiOverlay(aMap, poiItems);
                        poiOverlay.removeFromMap();
                        poiOverlay.addToMap();
                        poiOverlay.zoomToSpan();
                    } else if (suggestionCities != null
                            && suggestionCities.size() > 0) {
                        showSuggestCity(suggestionCities);
                    } else {
                        Toast.makeText(MainActivity.this,"沒有可顯示的結果",Toast.LENGTH_SHORT).show();
                    }
                }
            } else {
                Toast.makeText(MainActivity.this,"沒有可顯示的結果",Toast.LENGTH_SHORT).show();
            }
        } else if (rCode == 27) {
            Toast.makeText(MainActivity.this,"網絡錯誤",Toast.LENGTH_SHORT).show();
        } else if (rCode == 32) {
            Toast.makeText(MainActivity.this,"錯誤的Key值",Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this,"其他的錯誤",Toast.LENGTH_SHORT).show();
        }
    }

    //OnMapClickListener未實作的方法
    @Override
    public void onMapClick(LatLng latLng) {
    locationMarker=aMap.addMarker(new MarkerOptions().anchor(0.5f, 1)
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.end))
        .position(latLng).title("點選選取此點為中心"));
        locationMarker.showInfoWindow();
    }

    //OnInfoWindowClickListener未實作的方法
    @Override
    public void onInfoWindowClick(Marker marker) {
    locationMarker.hideInfoWindow();
        lp_current=new LatLonPoint(locationMarker.getPosition().latitude,
                locationMarker.getPosition().longitude);
        Log.i("選點Lp",lp_current+"");
        locationMarker.destroy();
    }

    //OnClickListener未實作的方法
    @Override
    public void onClick(View v) {
    switch (v.getId()){
        case R.id.Button:
            aMap.clear();
            registerListener();
            break;
        /*case R.id.nextButton: //點選擷取下一頁資料
           nextSearch();
            break;*/
    }
    }
    private void showSuggestCity(List<SuggestionCity> cities) {
        String infomation = "推薦城市\n";
        for (int i = 0; i < cities.size(); i++) {
            infomation += "城市名稱:" + cities.get(i).getCityName() + "城市區号:"
                    + cities.get(i).getCityCode() + "城市編碼:"
                    + cities.get(i).getAdCode() + "\n";
        }
        Toast.makeText(MainActivity.this,infomation,Toast.LENGTH_SHORT).show();

    }
    protected void doSearchQuery(String name, String type, String city) {
        // showProgressDialog();// 顯示進度框
        aMap.setOnMapClickListener(null);// 進行poi搜尋時清除掉地圖點選事件
        currentPage = 0;
        query = new PoiSearch.Query(name, type, city);// 第一個參數表示搜尋字元串,第二個參數表示poi搜尋類型,第三個參數表示poi搜尋區域(空字元串代表全國)
        query.setPageSize(20);// 設定每頁最多傳回多少條poiitem
        query.setPageNum(currentPage);// 設定查第一頁
        searchType = tsearchType;

        //選擇是否團購
        /**
        switch (searchType) {
            case 0: {// 所有poi
                query.setLimitDiscount(false);
                query.setLimitGroupbuy(false);
            }
            break;
            case 1: {// 有團購
                query.setLimitGroupbuy(true);
                query.setLimitDiscount(false);
            }
            break;
            case 2: {// 有優惠
                query.setLimitGroupbuy(false);
                query.setLimitDiscount(true);
            }
            break;
            case 3: {// 有團購或者優惠
                query.setLimitGroupbuy(true);
                query.setLimitDiscount(true);
            }
            break;
        }*/
        if (lp_current != null) {
            poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(this);
            poiSearch.setBound(new PoiSearch.SearchBound(lp_current, 2000, true));//
            // 設定搜尋區域為以lp點為圓心,其周圍2000米範圍
            /*
             * List<LatLonPoint> list = new ArrayList<LatLonPoint>();
             * list.add(lp);
             * list.add(AMapUtil.convertToLatLonPoint(Constants.BEIJING));
             * poiSearch.setBound(new SearchBound(list));// 設定多邊形poi搜尋範圍
             */
            poiSearch.searchPOIAsyn();// 異步搜尋
        }
    }
    /**
     * 注冊監聽
     */
    private void registerListener() {
        aMap.setOnMapClickListener(MainActivity.this);
        aMap.setOnMarkerClickListener(MainActivity.this);
        aMap.setOnInfoWindowClickListener(this);
        aMap.setInfoWindowAdapter(MainActivity.this);
    }
    /**
     * 點選下一頁poi搜尋(暫時未設定點選進入下一頁的Button,如若需要請自行添加)
     */
    public void nextSearch() {
        if (query != null && poiSearch != null && poiResult != null) {
            if (poiResult.getPageCount() - 1 > currentPage) {
                currentPage++;

                query.setPageNum(currentPage);// 設定查後一頁
                poiSearch.searchPOIAsyn();
            } else {
                Toast.makeText(MainActivity.this,"沒有可顯示的結果",Toast.LENGTH_SHORT).show();
            }
        }
    }
}