Android 高德地图 定位+围栏

package com.amap.map3d.demo;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.amap.api.fence.GeoFence;
import com.amap.api.fence.GeoFenceClient;
import com.amap.api.fence.GeoFenceListener;
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.location.DPoint;
import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.CircleOptions;
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.jetbrains.annotations.Nullable;

import java.util.List;

/**
 * Created by PVer on 2018/4/9.
 */

public class DingweiActivity extends Activity implements AMapLocationListener, GeoFenceListener {
    private AMapLocationClient aMapLocationClient;
    private AMapLocationClientOption locationClientOption;
    private AMap aMap;
    private MapView mapView;
    private MyBroadcastReceiver mBReceiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);
        init();
        showLocationIcon();
        createMark();
        create();
//围栏初始化
 //注册监听事件
        mGeoFenceClient = new GeoFenceClient(getApplicationContext());
        mGeoFenceClient.setActivateAction(GeoFenceClient.GEOFENCE_IN| GeoFenceClient.GEOFENCE_OUT| GeoFenceClient.GEOFENCE_STAYED);
        mGeoFenceClient.createPendingIntent(GEOFENCE_BROADCAST_ACTION);
//接受定位广播
        IntentFilter filter = new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(GEOFENCE_BROADCAST_ACTION);
        mBReceiver = new MyBroadcastReceiver();
        registerReceiver(mBReceiver, filter);


    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState),保存地图当前的状态
        mapView.onSaveInstanceState(outState);
    }

    //---------------todo  定位代码---------------------------------------------------------------------
    public void init() {
        aMap = mapView.getMap();
        aMapLocationClient = new AMapLocationClient(this);
        locationClientOption = new AMapLocationClientOption();
        //设置返回地址信息,默认为true
        locationClientOption.setNeedAddress(true);
//设置定位监听
//设置定位模式为高精度模式,Battery_Saving为低功耗模式,Device_Sensors是仅设备模式
        locationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
        locationClientOption.setInterval(2000);
        aMapLocationClient.setLocationListener(DingweiActivity.this);//定位监听 获取定位信息onLocationChanged()
        aMapLocationClient.setLocationOption(locationClientOption);
        aMapLocationClient.startLocation();
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        StringBuffer sb = new StringBuffer();
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                sb.append("定位成功" + "\n");
                sb.append("定位类型: " + aMapLocation.getLocationType() + "\n");
                sb.append("经    度    : " + aMapLocation.getLongitude() + "\n");
                sb.append("纬    度    : " + aMapLocation.getLatitude() + "\n");
                sb.append("精    度    : " + aMapLocation.getAccuracy() + "米" + "\n");
                sb.append("提供者    : " + aMapLocation.getProvider() + "\n");

                sb.append("速    度    : " + aMapLocation.getSpeed() + "米/秒" + "\n");
                sb.append("角    度    : " + aMapLocation.getBearing() + "\n");
                // 获取当前提供定位服务的卫星个数
                sb.append("星    数    : " + aMapLocation.getSatellites() + "\n");
                sb.append("国    家    : " + aMapLocation.getCountry() + "\n");
                sb.append("省            : " + aMapLocation.getProvince() + "\n");
                sb.append("市            : " + aMapLocation.getCity() + "\n");
                sb.append("城市编码 : " + aMapLocation.getCityCode() + "\n");
                sb.append("区            : " + aMapLocation.getDistrict() + "\n");
                sb.append("区域 码   : " + aMapLocation.getAdCode() + "\n");
                sb.append("地    址    : " + aMapLocation.getAddress() + "\n");
                sb.append("兴趣点    : " + aMapLocation.getPoiName() + "\n");
                //定位完成的时间
      //              sb.append("定位时间: " + Utils.formatUTC(aMapLocation.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");

                //Log.e("tag", sb.toString());
            }
        }
    }

    //todo------------定位图标与map  的关联-----------------------------------------
    private MyLocationStyle myLocationStyle;

    public void showLocationIcon() {
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点,定位点依照设备方向旋转,并且会跟随设备移动。(1秒1次定位)如果不设置myLocationType,默认也会执行此种模式。
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔,只在连续定位模式下生效,单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//定位模式 不跟随   默认情况下跟随
        aMap.setMyLocationStyle(myLocationStyle);  //图片与map 相互关联
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示,非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点,false表示隐藏定位蓝点并不进行定位,默认是false。


    }


    //todo -----------------創建圍欄创建围栏  并监听 围栏事件--------
    private GeoFenceClient mGeoFenceClient;

    public void showWeiLan(double v1, double v2) {
        //创建自定义 围栏   圆形//创建一个中心点坐标
        DPoint centerPoint = new DPoint(v1, v2);
        mGeoFenceClient.addGeoFence(centerPoint, 300f, "1");
        //围栏监听信息
        mGeoFenceClient.setGeoFenceListener(this);
        Log.e("tag", "============围栏300==================1");
    }

    //绘制面
    public void circle(double v1, double v2) {
        LatLng latLng = new LatLng(v1, v2);

        aMap.addCircle(new CircleOptions().center(latLng)
                .radius(300).strokeColor(Const.STROKE_COLOR)
                .fillColor(Const.FILL_COLOR).strokeWidth(Const.STROKE_WIDTH));
        Log.e("tag", "============圈圈300==================2");
    }

    //点击地图任意一个地方创建围栏
    public void create() {
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {

                Log.e("经纬度", latLng.latitude + "/" + latLng.longitude);
                circle(latLng.latitude, latLng.longitude);
                showWeiLan(latLng.latitude, latLng.longitude);
            }
        });
    }

    //围栏监听信息
    @Override
    public void onGeoFenceCreateFinished(List<GeoFence> list, int i, String s) {
        if (i == GeoFence.ADDGEOFENCE_SUCCESS) {//判断围栏是否创建成功
            //geoFenceList就是已经添加的围栏列表
            //    Toast.makeText(DingweiActivity.this, "yy", Toast.LENGTH_SHORT).show();
            Log.e("ee", "创建围栏成功");
            //创建并设置PendingIntent  发送广播

        } else {
            //geoFenceList就是已经添加的围栏列表
            Log.e("ee", "创建围栏失敗");
        }
    }

    //todo -------------------------------------------------------------------

    //定义接收广播的action字符串
    public static final String GEOFENCE_BROADCAST_ACTION = "com.location.apis.geofencedemo.broadcast";

    class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(GEOFENCE_BROADCAST_ACTION)) {
                //解析广播内容
                Bundle bundle = intent.getExtras();
                //获取当前有触发的围栏对象:
                GeoFence fence = bundle.getParcelable(GeoFence.BUNDLE_KEY_FENCE);
                Toast.makeText(context, fence.getStatus() + "-----------", Toast.LENGTH_SHORT).show();
                int status = bundle.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS);
                StringBuffer sb = new StringBuffer();
                switch (status) {
                    case GeoFence.STATUS_LOCFAIL:
                        sb.append("定位失败");
                        break;
                    case GeoFence.STATUS_IN:
                        sb.append("进入围栏 ");
                        Toast.makeText(context, "enter围栏", Toast.LENGTH_SHORT).show();
                        Log.e("tttt", "进入围栏");
                        break;
                    case GeoFence.STATUS_OUT:
                        sb.append("离开围栏 ");
                        Toast.makeText(context, "离开围栏", Toast.LENGTH_SHORT).show();
                        Log.e("tttt", "离开围栏");
                        break;
                    case GeoFence.STATUS_STAYED:
                        sb.append("停留在围栏内 ");
                        Log.e("tttt", "停留围栏");
                        Toast.makeText(context, "停留围栏", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
            }
        }
    }


    /**
     * 添加mark
     */
    public void createMark() {
        //map  地图添加   监听mark     必须的
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                addMarkersToMap();
            }
        });

        //拖动地图  获取地图位置设置地图状态的监听接口。
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                Log.e("AAPP_CHANGE", cameraPosition.toString());
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {

                Log.e("AAPP_FINISH", cameraPosition.toString());
            }
        });// 对amap添加移动地图事件监听器
    }

    /**
     * 在地图上添加marker
     */
    private void addMarkersToMap() {
        addMarkerInScreenCenter();
    }

    /**
     * 在屏幕中心添加一个Marker
     */
    /**
     * 可视区域的位置(CameraPosition)
     * <p>
     * 可视区域的位置由以下属性组成:
     * <p>
     * 目的地(target)
     * 缩放级别(zoom)
     * 方向(bearing)
     * 倾斜角度(tilt)
     * <p>
     * 屏幕当前可视区域的位置可以通过 AMap.getCameraPosition() 方法获取。
     * 目的地(target)
     * 屏幕中心marker 跳动
     * <p>
     * 该mark  始终在屏幕的中心点 不跟随地图的移动而移动  因此在监听地图拖动监听事件时获取地理位置  也要进行中心点的判断
     * <p>
     * getCameraPosition()  和   aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {} CameraPosition  一致
     */
    Marker screenMarker = null;

    private void addMarkerInScreenCenter() {
        LatLng latLng = aMap.getCameraPosition().target;//  目的地(target)         缩放级别(zoom)       方向(bearing)        倾斜角度(tilt)
        Point screenPosition = aMap.getProjection().toScreenLocation(latLng);
        screenMarker = aMap.addMarker(new MarkerOptions()
                .anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.purple_pin)));
        //设置Marker在屏幕上,不跟随地图移动
        screenMarker.setPositionByPixels(screenPosition.x, screenPosition.y);


    }


    //通过Mark 所在的坐标点 获取    坐标获取   poi
/*
    public void getPoi() {
        PoiSearch  poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(locationMarker.getPosition().latitude,
                locationMarker.getPosition().longitude), 1000));//设置周边搜索的中心点以及半径

    }
*/

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy(),销毁地图
        mapView.onDestroy();
        aMapLocationClient.onDestroy();//销毁定位客户端,同时销毁本地定位服务。
        unregisterReceiver(mBReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume (),重新绘制加载地图
        mapView.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause (),暂停地图的绘制
        mapView.onPause();
    }

}
如图 :当创建 围栏所在的区域范围内包含自己所在的定点坐标  会提示 已经进入围栏 反之离开围栏

这里写图片描述
这里写图片描述

代码传送https://download.csdn.net/download/bxllove/10340794

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值