package com.mayi.fastdevelop.map;

import android.content.Context;

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.mayi.fastdevelop.bean.LocationBean;
import com.mayi.fastdevelop.util.LogUtils;

public class LocationUtils {


    public static void startLocation(Context context, final LocationCallback callback) {
        final AMapLocationClient mlocationClient = new AMapLocationClient(context);
        //设置定位监听
        mlocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        LogUtils.i("amapLocation" + amapLocation);
                        if (callback != null) {
                            LocationBean bean = new LocationBean();
                            bean.setAddress(amapLocation.getAddress());
                            bean.setCityName(amapLocation.getCity());
                            bean.setProvinceName(amapLocation.getProvince());
                            bean.setAreaName(amapLocation.getDistrict());
                            bean.setLatitude(String.valueOf(amapLocation.getLatitude()));
                            bean.setLongitude(String.valueOf(amapLocation.getLongitude()));
                            callback.onSuccess(bean);
                        }
                    } else {
                        String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                        LogUtils.e("AmapErr" + errText);
                        if (callback != null) {
                            callback.onFail(errText);
                        }
                    }
                } else {
                    String errText = "定位失败";
                    LogUtils.e("AmapErr" + errText);
                    if (callback != null) {
                        callback.onFail(errText);
                    }
                }
                mlocationClient.stopLocation();
                mlocationClient.onDestroy();
            }
        });
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        mLocationOption.setOnceLocationLatest(true);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setWifiScan(false);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        mlocationClient.startLocation();
    }


    public interface LocationCallback {

        public void onFail(String msg);

        public void onSuccess(LocationBean bean);

    }

}
