android 开发 我的高德地图代码例子

下载高德地图依赖库和相关注册方式,请查看高德开发者网站:http://lbs.amap.com/api/android-sdk/summary  点击打开链接

高德地图坐标拾取器:http://lbs.amap.com/console/show/picker   点击打开链接

 使用 keytool(jdk自带工具)获取SHA1

,按照如下步骤进行操作:

1.运行进入控制台。

2.在弹出的控制台窗口中输入 cd .android 定位到 .android 文件夹。

3.继续在控制台输入命令。

debug.keystore:命令为:keytool -list -v -keystore debug.keystore

自定义的 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) {
        //根据地址返回坐标的回调,不用到
    }

 

你可能感兴趣的:(android开发)