Android · 2016年12月15日 0

高德地图,定位 ,中间固定点拖动获取位置

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.LinearInterpolator;
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.CameraPosition;
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.animation.Animation;
import com.amap.api.maps.model.animation.RotateAnimation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.tlh.gczp.R;
import com.tlh.gczp.mvp.view.BaseUIActivity;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 地图选点
 */

public class AMapSelectPointActivity extends BaseUIActivity implements LocationSource {
    public static String TITLE_TAG = "title_str";//标题key
    public static String RESULT_TAG = "result_str";//返回数据key
    String titleStr = "地图";//标题

    @BindView(R.id.activity_amapselectpoint_map)
    MapView mMapView;
    @BindView(R.id.activity_amapselectpoint_text)
    TextView addressTxtView;//位置
    AMap aMap;//地图
    private UiSettings mUiSettings;//定义一个UiSettings对象

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    OnLocationChangedListener listener;


    MarkerOptions markerCenter = new MarkerOptions();//中心点

    Marker marker;//中间

    GeocodeSearch geocodeSearch;//地理位置查询

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentViewItem(R.layout.activity_amapselectpont);
        ButterKnife.bind(this);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState),实现地图生命周期管理
        mMapView.onCreate(savedInstanceState);
        rightBtn.setTextColor(Color.parseColor("#fcc900"));
        initData();
        showPage();
    }

    /**
     * 实例化数据
     */
    private void initData() {
        initMap();
        titleStr = getIntent().getStringExtra(TITLE_TAG);
        if (TextUtils.isEmpty(titleStr)){
            titleStr = "地图";
        }
        setPageName(titleStr);
        currentPageName = titleStr;
        setRightTxt(getString(R.string.str_common_finish), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchAddressByLat(marker.getPosition());
            }
        });

    }

    private void initMap() {//实例化Map
        geocodeSearch = new GeocodeSearch(this);
        //初始化地图变量
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);
        mUiSettings = aMap.getUiSettings();//实例化UiSettings类
        mUiSettings.setZoomControlsEnabled(true);
        //定位按钮
        aMap.setLocationSource(this);// 设置定位监听
        mUiSettings.setMyLocationButtonEnabled(true); // 显示默认的定位按钮
        aMap.setMyLocationEnabled(true);// 可触发定位并显示定位层

        mUiSettings.setScaleControlsEnabled(true);//显示比例尺控件
        mUiSettings.setAllGesturesEnabled(true);
        mUiSettings.setCompassEnabled(true);//指南针


//        LatLng latLng = new LatLng(39.906901, 116.397972);
//        final Marker marker = aMap.addMarker(new MarkerOptions().
//                position(latLng).
//                title("北京").
//                snippet("DefaultMarker"));

//        final Marker marker = aMap.addMarker(new MarkerOptions());
//        MarkerOptions markeroptions = new MarkerOptions();
//        markeroptions.position(latLng);
//        markeroptions.title("当前位置");
//        markeroptions.visible(true);
//        BitmapDescriptor bitmapDescriptor= BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),R.mipmap.positioning_normal));
//        markeroptions.icon(bitmapDescriptor);
//        aMap.addMarker(markeroptions);


       mMapView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
           @Override
           public void onGlobalLayout() {
               Log.e("mMapView","onGlobalLayout===---123");

                marker = aMap.addMarker(new MarkerOptions());
               Animation animation = new RotateAnimation(marker.getRotateAngle(), marker.getRotateAngle() + 720, 0, 0, 0);
               long duration = 1000L;
               animation.setDuration(duration);
               animation.setInterpolator(new LinearInterpolator());

               marker.setAnimation(animation);
               marker.startAnimation();
               marker.setPositionByPixels(mMapView.getWidth()/2, mMapView.getHeight()/2);
           }
       });


        LatLng ll = new LatLng(34.6006623972045,108.97923588752748);
        markerCenter.position(ll);
        markerCenter.visible(true);
        markerCenter.title("中心点");
//        BitmapDescriptor bitmapDescriptor= BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),R.mipmap.icon_nearby));
//        markerCenter.icon(bitmapDescriptor);
        aMap.addMarker(markerCenter);



        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy,高精度模式。
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);

        mLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (listener != null) {
                        listener.onLocationChanged(aMapLocation);
                    }
                    if (aMapLocation.getErrorCode() == 0) {
                        //可在其中解析amapLocation获取相应内容。
                        Log.e("AMapSelectPointActivity", "aMapLocation=" + aMapLocation.getCity());
                        Log.e("AMapSelectPointActivity", "aMapLocation address=" + aMapLocation.getAddress());

                    } else {
                        //定位失败时,可通过ErrCode(错误码)信息来确定失败的原因,errInfo是错误信息,详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
                    }
                }
                Log.e("AMapSelectPointActivity", "aMapLocation run  onLocationChanged");
            }
        };
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        mLocationClient.setLocationOption(mLocationOption);//设置模式
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                LatLng target = cameraPosition.target;
                System.out.println(target.latitude + "jinjin------" + target.longitude);
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                LatLng target = cameraPosition.target;
                System.out.println("changeFinish="+target.latitude + "jinjin------" + target.longitude);
                LatLng ll = new LatLng(target.latitude,target.longitude);
                markerCenter.position(ll);
                searchAddressByLat(ll);
//                markerCenter.visible(true);
//                markerCenter.title("中心点");
//                BitmapDescriptor bitmapDescriptor= BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),R.mipmap.icon_nearby));
//                markerCenter.icon(bitmapDescriptor);
//                aMap.addMarker(markerCenter);

            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理
        mMapView.onDestroy();
        mLocationClient.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume (),实现地图生命周期管理
        mMapView.onResume();
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause (),实现地图生命周期管理
        mMapView.onPause();
        mLocationClient.stopLocation();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState),实现地图生命周期管理
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        Log.e("AMapSelectPointActivity", "activate is run");
        listener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {//高德地图位置监听
        listener = null;
    }

    private  void searchAddressByLat(final LatLng latLng){
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
                if (rCode == 1000) {
                    if (result != null && result.getRegeocodeAddress() != null
                            && result.getRegeocodeAddress().getFormatAddress() != null) {
                        String addressName = result.getRegeocodeAddress().getFormatAddress()
                                + "附近";
                        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
                        addressTxtView.setText(result.getRegeocodeAddress().getFormatAddress());
                        Toast.makeText(AMapSelectPointActivity.this, addressName,Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(AMapSelectPointActivity.this, "未找到",Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(AMapSelectPointActivity.this, "失败",Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }
        });

        LatLonPoint point = new LatLonPoint(latLng.latitude,latLng.longitude);
        RegeocodeQuery query = new RegeocodeQuery(point, 200,GeocodeSearch.AMAP);
        geocodeSearch.getFromLocationAsyn(query);
    }
}

Share this: