1. 程式人生 > >android 高德地圖的接入的demo

android 高德地圖的接入的demo

   


import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
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.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.Date;

public class LocationAct extends BaseActivity implements AMap.InfoWindowAdapter ,LocationSource, AMapLocationListener{
    private boolean isFirstLoc = true;
    private AMap aMap;
    private MapView mMapView;
    MyLocationStyle myLocationStyle;

    //定位需要的宣告
    private AMapLocationClient mLocationClient = null;
    //定位發起端
    private AMapLocationClientOption mLocationOption = null;
    //定位引數
    private LocationSource.OnLocationChangedListener mListener = null;
    //定位監聽器 //標識,用於判斷是否只顯示一次定位資訊和使用者重新定位

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_location);
        x.view().inject(this);
        initview();
        // 在activity執行onCreate時執行mMapView.onCreate(savedInstanceState),建立地圖
        mMapView.onCreate(savedInstanceState);
        if (aMap==null){
            aMap=mMapView.getMap();
        }
        aMap.setInfoWindowAdapter(this);
       /* LatLng latLng = new LatLng(39.906901,116.397972);
        final Marker marker = aMap.addMarker(new MarkerOptions().position(latLng).title("北京").snippet("DefaultMarker"));*/
    /*    aMap.setInfoWindowAdapter(this);*/
    /*MarkerOptions markerOption = new MarkerOptions();
        LatLng XIAN = new LatLng(39.906901,116.397972);
        markerOption.position(XIAN);
        markerOption.title("西安市").snippet("西安市:34.341568, 108.940174");

        markerOption.draggable(true);//設定Marker可拖動
        markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(),R.drawable.marker_normal)));
        // 將Marker設定為貼地顯示,可以雙指下拉地圖檢視效果
        markerOption.setFlat(true);//設定marker平貼地圖效果
        Marker marker=aMap.addMarker(markerOption);*/
        /*LatLng latLng = new LatLng(39.906901,116.397972);
        final Marker marker = aMap.addMarker(new MarkerOptions().position(latLng).title("北京").snippet("DefaultMarker"));*/
        /*marker.showInfoWindow();*/
        //設定顯示定位按鈕 並且可以點選
        UiSettings settings = aMap.getUiSettings();
        //設定定位監聽
        aMap.setLocationSource(this);
        // 是否顯示定位按鈕
        settings.setMyLocationButtonEnabled(true);
        // 是否可觸發定位並顯示定位層
        aMap.setMyLocationEnabled(true);
        //定位的小圖示 預設是藍點 這裡自定義一團火,其實就是一張圖片
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.marker_normal));
        myLocationStyle.radiusFillColor(android.R.color.transparent);
        myLocationStyle.strokeColor(android.R.color.transparent);
        aMap.setMyLocationStyle(myLocationStyle);
        initLoc();

    }


    private void initview() {
        initHerderText("展館位置");
        initHerderRightImg(R.drawable.round);
        mMapView = (MapView) findViewById(R.id.map);//找到地圖控制元件

    }
    public static void startActivity(Context context, String id) {
        Intent intent = new Intent();
        intent.setClass(context, LocationAct.class);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }

    @Override
    public View getInfoWindow(Marker marker) {
        View infoWindow = getLayoutInflater().inflate(
                R.layout.location_custom_info_window, null);
        render(marker, infoWindow);
        return infoWindow;

    }

    @Override
    public View getInfoContents(Marker marker) {
        View infoWindow = getLayoutInflater().inflate(
                R.layout.location_custom_info_window, null);
        render(marker, infoWindow);
        return infoWindow;
    }
    /**     * 自定義infowinfow視窗,將自定義的infoWindow和Marker關聯起來   */
    public void render(Marker marker, View view) {
        String title = marker.getTitle();
        TextView titleUi = ((TextView) view.findViewById(R.id.inforwindow_name));
        titleUi.setText(title);
        String snippet = marker.getSnippet();
        TextView snippetUi = ((TextView) view.findViewById(R.id.inforwindow_text));
        snippetUi.setText(snippet);
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity執行onResume時執行mMapView.onResume (),重新繪製載入地圖
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity執行onPause時執行mMapView.onPause (),暫停地圖的繪製
        mMapView.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity執行onSaveInstanceState時執行mMapView.onSaveInstanceState (outState),儲存地圖當前的狀態
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity執行onDestroy時執行mMapView.onDestroy(),銷燬地圖
        mMapView.onDestroy();

    }
//定位
   private void initLoc()
   { //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //設定定位回撥監聽
       mLocationClient.setLocationListener(this);
       //初始化定位引數
       mLocationOption = new AMapLocationClientOption();
       //設定定位模式為高精度模式,Battery_Saving為低功耗模式,Device_Sensors是僅裝置模式
       mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
       //設定是否返回地址資訊(預設返回地址資訊)
       mLocationOption.setNeedAddress(true);
       //設定是否只定位一次,預設為false
       mLocationOption.setOnceLocation(false);
       //設定是否強制重新整理WIFI,預設為強制重新整理
       mLocationOption.setWifiActiveScan(true);
       //設定是否允許模擬位置,預設為false,不允許模擬位置
       mLocationOption.setMockEnable(false);
       //設定定位間隔,單位毫秒,預設為2000ms
       mLocationOption.setInterval(2000);
       //給定位客戶端物件設定定位引數
       mLocationClient.setLocationOption(mLocationOption);
       //啟動定位
       mLocationClient.startLocation();
   }

    @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();
            //省資訊
            amapLocation.getCity();
            //城市資訊
            amapLocation.getDistrict();
            //城區資訊
            amapLocation.getStreet();
            //街道資訊
            amapLocation.getStreetNum();
            //街道門牌號資訊
            amapLocation.getCityCode();
            //城市編碼
            amapLocation.getAdCode();
            //地區編碼 // 如果不設定標誌位,此時再拖動地圖時,它會不斷將地圖移動到當前的位置
            if (isFirstLoc) {
                // /設定縮放級別
                aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
                //將地圖移動到定位點
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude())));
                //點選定位按鈕 能夠將地圖的中心移動到定位點
                mListener.onLocationChanged(amapLocation);
                //新增圖釘
                Marker marker=aMap.addMarker(getMarkerOptions(amapLocation));
                marker.showInfoWindow();
                //獲取定位資訊
                 StringBuffer buffer = new StringBuffer();
                 buffer.append(amapLocation.getCountry() + "" + amapLocation.getProvince() + "" + amapLocation.getCity() + "" + amapLocation.getProvince() + "" + amapLocation.getDistrict() + "" + amapLocation.getStreet() + "" + amapLocation.getStreetNum()); Toast.makeText(getApplicationContext(), buffer.toString(), Toast.LENGTH_LONG).show();
                 isFirstLoc = false; } }
                 else {
            //顯示錯誤資訊ErrCode是錯誤碼,errInfo是錯誤資訊,詳見錯誤碼錶。
            Log.e("AmapError", "location Error, ErrCode:" + amapLocation.getErrorCode() + ", errInfo:" + amapLocation.getErrorInfo()); Toast.makeText(getApplicationContext(), "定位失敗", Toast.LENGTH_LONG).show(); }
           }

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mListener = null;

    }



    //自定義一個圖釘,並且設定圖示,當我們點選圖釘時,顯示設定的資訊
    private MarkerOptions getMarkerOptions(AMapLocation amapLocation)
    {
        //設定圖釘選項
        MarkerOptions options = new MarkerOptions();
        //圖示
        options.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_selected));
        //位置
        options.position(new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude()));
        StringBuffer buffer = new StringBuffer(); buffer.append(amapLocation.getCountry() + "" + amapLocation.getProvince() + "" + amapLocation.getCity() + "" + amapLocation.getDistrict() + "" + amapLocation.getStreet() + "" + amapLocation.getStreetNum());
        //標題
        options.title(buffer.toString());
        //子標題
        options.snippet("lallalllaalalalhyy");
        //設定多少幀重新整理一次圖片資源
        options.period(60);
        return options;
    }

}