android 開發 個人高德地圖代碼例子

下載高德地圖依賴庫和相關注冊方式,請查看高德開發者網站:http://lbs.amap.com/api/android-sdk/summary  點擊打開連接java

高德地圖座標拾取器:http://lbs.amap.com/console/show/picker   點擊打開連接android

 使用 keytool(jdk自帶工具)獲取SHA1git

,按照以下步驟進行操做:api

1.運行進入控制檯。安全

2.在彈出的控制檯窗口中輸入 cd .android 定位到 .android 文件夾。網絡

3.繼續在控制檯輸入命令。app

debug.keystore:命令爲:keytool -list -v -keystore debug.keystoreide

自定義的 keystore:命令爲:keytool -list -v -keystore apk的keystore工具

以下所示:佈局

提示輸入密鑰庫密碼,編譯器提供的debug keystore默認密碼是 android,自定義簽名文件的密碼請自行填寫。輸入密鑰後回車(若是沒設置密碼,可直接回車),此時可在控制檯顯示的信息中獲取 SHA1 值,以下圖所示:

說明:keystore 文件爲 Android 簽名證書文件。

 

例子1:

package com.example.lenovo.mydemoapp;

import android.content.Intent;
import android.graphics.Point;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
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.AMapUtils;
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.CameraPosition;
import com.amap.api.maps.model.LatLng;

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

/*
name:編輯安全區
time:2018-06-09 11:32:22
Can Enter:1.安全區信息確認 SafeAreaConfirmation
return:1.高德地圖的經緯度座標值  2.圍欄的半徑大小
returnActivity:1.安全區
 */
// LocationSource 定位按鍵的監聽接口
public class EditSafeArea extends AppCompatActivity implements LocationSource,AMap.OnCameraChangeListener,AMapLocationListener {
    private SeekBar mSeekBar ;
    //半徑顯示的文本View
    private TextView mRadiusValue;
    private View mEditSafeAreaMapFence;
    //下一步
    private TextView mEditSafeAreaTheNextStepText;
    //aMap 地圖對象
    private AMap aMap;
    //地圖視圖
    private MapView mapView;
    //聲明AMapLocationClient 地圖位置客戶端 對象,定位發起端
    private AMapLocationClient mLocationClient = null;
    //聲明mLocationOption  地圖位置客戶端選項 對象,定位參數  `
    public AMapLocationClientOption mLocationOption = null;
    //聲明mListener對象,定位監聽器
    private OnLocationChangedListener mListener = null;
    //標識,用於判斷是否只顯示一次定位信息和用戶從新定位
    private boolean isFirstLoc = true;
    private AMapLocation aMapLocation ;
    private int mRadius;
    private LatLng mLatlng;
    private final String LATITUDE_KEY = "latitude_value";
    private final String LONGITUDE_KEY = "longitude_value";
    private final String RADIUS_KEY = "radius_value";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_safe_area);
        //圍欄
        mEditSafeAreaMapFence = (View)findViewById(R.id.EditSafeArea_MapFence);
        //拖動條
        mSeekBar = (SeekBar)findViewById(R.id.EditSafeArea_SeekBar);
        //半徑顯示文本
        mRadiusValue = (TextView)findViewById(R.id.EditSafeArea_radius_value);
        //下一步
        mEditSafeAreaTheNextStepText = (TextView)findViewById(R.id.EditSafeArea_TheNextStep_text);
        //獲取地圖控件
        mapView = (MapView)findViewById(R.id.EditSafeArea_MapView);
        //在activity執行onCreate時執行mMapView.onCreate(savedInstanceState),實現地圖生命週期管理
        mapView.onCreate(savedInstanceState);
        if(aMap == null){
            //建立地圖對象
            aMap = mapView.getMap();
            //建立UI設置器
            UiSettings settings = aMap.getUiSettings();
            //地點變化監聽器
            aMap.setLocationSource(this);
            //當前鏡頭變化監聽器
            aMap.setOnCameraChangeListener(this);
            // 是否顯示定位按鈕
            settings.setMyLocationButtonEnabled(true);
            //定位圖標是否能夠點擊
            aMap.setMyLocationEnabled(true);
        }
        //開始定位
        location();
        //設置拖動條默認值
        mSeekBar.setProgress(0);
        //設置拖動條默認值的顯示 ,由於默認是400 因此這裏添加400
        mRadiusValue.setText(Integer.toString(mSeekBar.getProgress()+400));
        //顯示默認圍欄的大小
        mEditSafeAreaMapFence.setLayoutParams(setFence());
        //拖動條監聽
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //拖動條拖動後更新文本值
                mRadiusValue.setText(Integer.toString(progress+400));
                //更新圍欄的範圍
                mEditSafeAreaMapFence.setLayoutParams(setFence());
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        //下一步監聽
        mEditSafeAreaTheNextStepText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EditSafeArea.this,SafeAreaConfirmation.class);
                if(mLatlng == null || mLatlng == null  || mRadius == 0 ){
                    Toast.makeText(EditSafeArea.this,"沒有定位成功",Toast.LENGTH_SHORT).show();
                }else {
                    intent.putExtra(LATITUDE_KEY,mLatlng.latitude);
                    intent.putExtra(LONGITUDE_KEY,mLatlng.longitude);
                    intent.putExtra(RADIUS_KEY,mRadius);
                    Log.e("EditSafeArea","傳出的mLatlng是:"+mLatlng.latitude);
                    Log.e("EditSafeArea","傳出的longitude是:"+mLatlng.longitude);
                    Log.e("EditSafeArea","傳出的半徑值是:"+mRadius);
                    startActivity(intent);
                }


            }
        });

    }
    private void location() {

        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //設置定位按鍵的監聽
        mLocationClient.setLocationListener(this);
        //初始化定位參數  mLocationOption 定位的參數設置
        mLocationOption = new AMapLocationClientOption();
        //設置定位模式爲Hight_Accuracy高精度模式,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(5000);
        //給定位客戶端對象設置定位參數
        mLocationClient.setLocationOption(mLocationOption);
        //啓動定位
        mLocationClient.startLocation();

    }
    //由於地圖的生命週期管理必需要與活動的生命週期管理捆綁,因此必須重寫方法
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stopLocation();//中止定位
        mLocationClient.onDestroy();//銷燬地圖
    }
    //必須重寫的方法
    @Override
    protected void onResume() {
        super.onResume();
        //從新恢復地圖
        mapView.onResume();
    }
    //必須重寫的方法
    @Override
    protected void onPause() {
        super.onPause();
        //暫停地圖
        mapView.onPause();
    }
    //必須重寫的方法
    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        mapView.onSaveInstanceState(outState);
    }

    /*
    定位參數回調   這個方法還有一個屬性:若是以前已經定位了,而且添加了定位圖標,那麼每次手動點擊定位按鍵回調這個方法
    ,就會在地圖上執行一次自動回到定位點上
     */

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        this.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();//地區編碼
                LatLng latLng = new LatLng(aMapLocation.getLatitude(),aMapLocation.getLongitude());
                if (isFirstLoc) {
                    //設置縮放級別    moveCamera 移動相機   CameraUpdateFactory 相機更新制做  zoomBy 放大
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
                    //將地圖移動到定位點,僅僅是將地圖位置移動到定位點
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                    //獲取定位信息
                    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;
                    Log.e("EditSafeArea","定位後的布爾值:"+isFirstLoc);
                }
             } 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) {
        Log.e("EditSafeArea","定位按鍵啓動");
        //監聽    onLocationChangedListener 定位位置變化監聽器
        aMap.clear();
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));

        mListener = onLocationChangedListener;

    }
    //定位按鍵完成關閉後回調的方法
    @Override
    public void deactivate() {
        mListener = null;

    }

    //地圖鏡頭有動的狀況下回調
    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        mLatlng = cameraPosition.target;
        mEditSafeAreaMapFence.setLayoutParams(setFence());
        }

    //地圖鏡頭不動的回調
    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        mLatlng = cameraPosition.target;
        LatLng latLng  = cameraPosition.target;

    }
    //設置圍欄的方法
    public ViewGroup.LayoutParams setFence(){
        mRadius = Integer.parseInt(mRadiusValue.getText().toString());
        //獲得手機屏幕上的一個座標
        Point point = new Point();
        point.x = 0;
        point.y = 0;
        //獲得手機屏幕上的另一個座標
        Point point1 = new Point();
        point1.x = 0;
        point1.y = 200;
        //根據座標獲取地圖上對應經緯
        LatLng latLng = aMap.getProjection().fromScreenLocation(point);
        LatLng latLng1 = aMap.getProjection().fromScreenLocation(point1);
        Log.e("EditSafeArea","latLng_latitude:"+latLng.latitude+"latLng_longitude:"+latLng.longitude);
        Log.e("EditSafeArea","latLng1_latitude:"+latLng1.latitude+"latLng1_longitude:"+latLng1.longitude);
        //根據2組經緯度計算之間的直線長度,單位是米
        float distance = AMapUtils.calculateLineDistance(latLng,latLng1);
        Log.e("EditSafeArea","distance:"+distance);
        //建立佈局參數
        ViewGroup.LayoutParams layoutParams;
        layoutParams = mEditSafeAreaMapFence.getLayoutParams();
        //根據比例計算出圍欄須要對應的大小
        int d = (int)(200 * mRadius / distance);
        //導入大小值  加200是爲了在 安全區信息確認 的圍欄大小顯示統一,安全區信息確認的圍欄大小顯示是準確值
        layoutParams.width = d+200;
        layoutParams.height = d+200;
        return  layoutParams;

    }
}

 

例子2:

package com.example.lenovo.mydemoapp;

import android.content.Intent;
import android.graphics.Color;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;

/*
name:安全區信息確認
time:2018-06-09 11:32:22
Can Enter:1.保存 (返回安全區SafePlace)
return:1.高德地圖座標經緯度 2.圍欄的半徑 3.安全區名稱
returnActivity:SafePlace
 */
public class SafeAreaConfirmation extends AppCompatActivity {
    private MapView mapView;
    private AMap aMap;
    private EditText mSafeAreaConfirmationEditText;
    private Button mSafeAreaConfirmationSave;
    //地圖定位客戶端 對象.定位發起端口
    private AMapLocationClient mLocationClient;
    //  地圖位置客戶端選項 對象,定位參數  `
    private AMapLocationClientOption mLocationOption;
    //
    private int mRadius ;
    private double mLatitude;
    private double mLongitude;
    //傳入/傳出值的key
    private final String LATITUDE_KEY = "latitude_value";
    private final String LONGITUDE_KEY = "longitude_value";
    private final String RADIUS_KEY = "radius_value";
    private final String NAME_KEY = "name_value";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_safe_area_confirmation);
        mSafeAreaConfirmationEditText = (EditText)findViewById(R.id.SafeAreaConfirmation_EditText);
        mSafeAreaConfirmationSave = (Button)findViewById(R.id.SafeAreaConfirmation_save);
        mapView = (MapView)findViewById(R.id.SafeAreaConfirmation_MapView);
        mapView.onCreate(savedInstanceState);
        if(aMap == null){
            aMap = mapView.getMap();
            UiSettings uiSettings = aMap.getUiSettings();
            //不顯示定位按鍵
            uiSettings.setMyLocationButtonEnabled(false);
            //不顯示縮放圖標
            uiSettings.setZoomControlsEnabled(false);
            //設置爲不可使用縮放手勢
            uiSettings.setZoomGesturesEnabled(false);
            //設置爲不可使用滑動手勢
            uiSettings.setScrollGesturesEnabled(false);
            //設置爲不可使用旋轉手勢
            uiSettings.setRotateGesturesEnabled(false);
            //定位圖標不能夠點擊
            aMap.setMyLocationEnabled(false);
        }
        location();
        displayFence();
        //保存按鍵點擊事件
        mSafeAreaConfirmationSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSafeAreaConfirmationEditText.getText().toString().equals("")){
                    Toast.makeText(SafeAreaConfirmation.this,"請輸出安全區名稱",Toast.LENGTH_SHORT).show();
                    Log.e("SafeAreaConfirmation","文本框中的值是空的");
                }else {
                    Log.e("SafeAreaConfirmation","文本框中的值是:"+mSafeAreaConfirmationEditText.getText().toString());
                    Intent intent = new Intent(SafeAreaConfirmation.this,SafePlace.class);
                    intent.putExtra(LATITUDE_KEY,mLatitude);
                    intent.putExtra(LONGITUDE_KEY,mLongitude);
                    intent.putExtra(RADIUS_KEY,mRadius);
                    intent.putExtra(NAME_KEY,mSafeAreaConfirmationEditText.getText().toString());
                    startActivity(intent);
                }

            }
        });
    }

    //由於地圖的生命週期管理必需要與活動的生命週期管理捆綁,因此必須重寫方法
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stopLocation();//中止定位
        mLocationClient.onDestroy();//銷燬地圖
    }
    //必須重寫的方法
    @Override
    protected void onResume() {
        super.onResume();
        //從新恢復地圖
        mapView.onResume();
    }
    //必須重寫的方法
    @Override
    protected void onPause() {
        super.onPause();
        //暫停地圖
        mapView.onPause();
    }
    //必須重寫的方法
    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        mapView.onSaveInstanceState(outState);
    }
    //初始化地圖參數
    private void location() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //初始化定位參數  mLocationOption 定位的參數設置
        mLocationOption = new AMapLocationClientOption();
        //設置定位模式爲Hight_Accuracy高精度模式,Battery_Saving爲低功耗模式,Device_Sensors是僅設備模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //設置是否只定位一次,默認爲false
        mLocationOption.setOnceLocation(true);
        //設置是否強制刷新WIFI,默認爲強制刷新
        mLocationOption.setWifiActiveScan(true);
        //設置是否容許模擬位置,默認爲false,不容許模擬位置
        mLocationOption.setMockEnable(false);
        //設置定位間隔,單位毫秒,默認爲2000ms
        mLocationOption.setInterval(5000);
        //給定位客戶端對象設置定位參數
        mLocationClient.setLocationOption(mLocationOption);
    }

    //在地圖中畫圍欄
    public void displayFence(){
        Intent intent = getIntent();
        mLatitude = intent.getDoubleExtra(LATITUDE_KEY,0);
        mLongitude = intent.getDoubleExtra(LONGITUDE_KEY,0);
        mRadius = intent.getIntExtra(RADIUS_KEY,0);
        //圓選項
        CircleOptions circleOptions = new CircleOptions();
        if(mLatitude != 0 && mLongitude != 0 && mRadius != 0){
            LatLng latLng = new LatLng(mLatitude,mLongitude);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
            //設置地圖放大顯示級別
            if (mRadius < 200){
                aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
            }else if(mRadius < 400){
                aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
            }else if (mRadius < 700){
                aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
            }else if (mRadius <= 1300){
                aMap.moveCamera(CameraUpdateFactory.zoomTo(14));
            }
            // 導入座標
            circleOptions.center(latLng);
            // 設置半徑
            Log.e("SafeAreaConfirmation","radius is:"+mRadius);
            circleOptions.radius(mRadius);
            // 設置畫筆寬度
            circleOptions.strokeWidth(4);
            //畫筆顏色
            circleOptions.strokeColor(Color.argb(255,0,140,237));
            //填色
            circleOptions.fillColor(Color.argb(50,99,184,255));
            aMap.addCircle(circleOptions);

        }else {
            Log.e("SafeAreaConfirmation","latitude and longitude and radius is empty");
        }




    }
}

地圖上的標記自定義:

//設置地圖標記
    public void addMapMark(int position){
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(listData.getLatLng());
        markerOption.title(listData.getName());
        markerOption.draggable(false);
        Bitmap bt = BitmapFactory.decodeFile(listData.getFilePath());
        if(bt != null){
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeFile(listData.getFilePath())));
        }else {
            Log.e(TAG, "沒有獲取到頭像,使用默認頭像");
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(getResources(),R.mipmap.default_avatar1)));
        }

        aMap.addMarker(markerOption);
    }

根據座標得到地址:

首先要在class裏接口:

public class MainActivity extends BaseActivity implements GeocodeSearch.OnGeocodeSearchListener

而後傳入座標值

/**
     * 獲得地圖地址信息
     * @param latLng 座標值
     */
    public void getAddress(LatLng latLng){
        geocodeSearch = new GeocodeSearch(this);
        geocodeSearch.setOnGeocodeSearchListener(this);
        Log.e(TAG, "getAddress 座標值:"+"latitude:" +latLng.latitude+"longitude:"+latLng.longitude);
        LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude,latLng.longitude);
        RegeocodeQuery regeocodeQuery = new RegeocodeQuery(latLonPoint,200,GeocodeSearch.AMAP);//發生送座標、範圍、座標系
        geocodeSearch.getFromLocationAsyn(regeocodeQuery);
    }

得到座標的地圖地址文本回調

@Override  //根據座標返回文本地址的回調接口
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        //1000 是高德官方指定的成功的回返碼
        if( i == 1000){
            Log.e(TAG, "onRegeocodeSearched回調碼i: "+i );
            RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
            address = regeocodeAddress.getFormatAddress();
            Log.e(TAG, "onRegeocodeSearched地址: "+mAddress);
            mAddress.setText(address);
        }else {
            Log.e(TAG, "onRegeocodeSearched回調碼i: "+i );
        }

    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
        //根據地址返回座標的回調,不用到
    }
相關文章
相關標籤/搜索