高德地图,实际的项目,希望对您有借鉴意义

高德地图,点地图上任意一点,出现marker图标,并显示出地图的文字地址。同时能得到经纬度。能够搜索地址。

这里写图片描述


/**
 * Created by 张玉水 on 2016/7/18.
 */
public class ServiceLocationActivity extends TitleBaseActicity implements AMap.OnMapClickListener, AMap.OnCameraChangeListener, LocationSource, AMapLocationListener, View.OnClickListener, GeocodeSearch.OnGeocodeSearchListener {

    private MyEditText service_location_myet;
    public static  MapView mapView;
    private AMap aMap;
    private ScrollView scrollView;
    private MapContainer map_container;
    private Marker locationMarker;
    private Handler handler = new Handler();
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private boolean isFirstLoc=true;
    private OnLocationChangedListener mListener;
    private TextView tv_conform;
    private TextView tv_cancel;
    private GeocodeSearch geocoderSearch;
    private MarkerOptions marker;
    private LatLng markerLatLng;
    private String addressName;
    private TextView tv_undermap;
    private ImageView iv_search;
    private EditText et_address_search;


    @Override
    public void onCreateActionBar(Context context) {
        setCommonActionBar("服务地址");
    }

    @Override
    public void onActionBarCreated(View view) {
        super.onActionBarCreated(view);
        view.findViewById(R.id.actionbar_back).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                ComplteUserActivity.actionComplteUser(ServiceLocationActivity.this);
                finish();
            }
        });
    }

    public static void actionServiceLocation(Activity context){
        Intent intent = new Intent(context , ServiceLocationActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_location);

        scrollView = (ScrollView) findViewById(R.id.scrollview);
        map_container = (MapContainer) findViewById(R.id.map_container);
        tv_conform = (TextView) findViewById(R.id.confirm);
        tv_cancel = (TextView) findViewById(R.id.cancel);
        tv_undermap = (TextView) findViewById(R.id.tv_undermap);
        iv_search = (ImageView) findViewById(R.id.iv_search);
        et_address_search = (EditText) findViewById(R.id.et_address_search);
        tv_conform.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
        iv_search.setOnClickListener(this);

        map_container.setScrollView(scrollView);

        service_location_myet = (MyEditText) findViewById(R.id.service_location_myet);
        service_location_myet.hint("我们将感觉该地址为您优先推荐附近的客源");

        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写


        init();

    }


    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
        //移动当前视图到一个指定的经纬度
        double[] location = new GetLocationUtils(this).getLocation();
        LatLng latlng;
        if (location!=null){
            latlng= new LatLng(location[1],location[0]);
        }else {
            latlng=new LatLng(39.90403, 116.407525);
        }
        aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(
                latlng,18,0,30)));
    }

    /**
     * **往地图上添加一个marker**
     */
    private void setUpMapMarker(LatLng latLng) {

        markerLatLng=latLng;
        LatLonPoint latlonpoint=new LatLonPoint(latLng.latitude,latLng.longitude);
//        LatLonPoint latlonpoint=new LatLonPoint(latLng.longitude,latLng.latitude);

        //latLonPoint参数表示一个Latlng,第二参数表示范围多少米,GeocodeSearch.AMAP表示是国测局坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(latlonpoint, 200f,GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);

        aMap.clear();
        marker = new MarkerOptions().position(markerLatLng)
                .title("您选择的位置").snippet("正在查找...")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));

        aMap.addMarker(marker).showInfoWindow();



    }
    /**
     * 往地图上添加多个marker.并带有描述
     */
    private void addMapMarkersBySearch(LatLng latLng[],String desc[]) {
        aMap.clear();
        for (int i=0;i<latLng.length;i++){
            MarkerOptions marker = new MarkerOptions().position(latLng[i])
                    .title("搜索的位置").snippet(desc[i])
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
            //如果不加.showInfoWindow(),点击marker的时候才会点击出现文字描述。
            aMap.addMarker(marker).showInfoWindow();

        }
    }


    /**
     * amap添加一些事件监听器
     */
    private void setUpMap() {
        aMap.setOnMapClickListener(this);// 对amap添加单击地图事件监听器
        //aMap.setOnMapLongClickListener(this);// 对amap添加长按地图事件监听器
        aMap.setOnCameraChangeListener(this);// 对amap添加移动地图事件监听器

        UiSettings settings = aMap.getUiSettings();
        aMap.setLocationSource(this);//设置了定位的监听,这里要实现LocationSource接口
        // 是否显示定位按钮
        settings.setMyLocationButtonEnabled(true);
        aMap.setMyLocationEnabled(true);//显示定位层并且可以触发定位,默认是flase
          //地理编码和逆地理编码的设置回调监听
        geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(this);

        initLocation();

    }
    //初始化定位
    public void initLocation(){
        showProgressDialog(this);
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听,这里要实现AMapLocationListener接口,AMapLocationListener接口
        // 只有onLocationChanged方法可以实现,用于接收异步返回的定位结果,参数是AMapLocation类型。
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为Hight_Accuracy高精度模式,Battery_Saving为低功耗模式,Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setGpsFirst(false);
        //设置是否返回地址信息(默认返回地址信息)
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否强制刷新WIFI,默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false,不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        mapView=null;
        mLocationClient.stopLocation();//停止定位
        mLocationClient.onDestroy();//销毁定位客户端。
        //销毁定位客户端之后,若要重新开启定位请重新New一个AMapLocationClient对象。
    }

    /**
     * 对单击地图事件回调
     */
    @Override
    public void onMapClick(LatLng latLng) {
        setUpMapMarker(latLng);//点击地图,加入marker图标
    }

    /**
     * 对正在移动地图事件回调
     */
    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    /**
     * 对移动地图结束事件回调
     */
    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {

    }

    //地图定位
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mListener=null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        dismissProgressDialog();
        addressName = "";
        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();//地区编码

                // 如果不设置标志位,此时再拖动地图时,它会不断将地图移动到当前的位置
                if (isFirstLoc) {
                    //设置缩放级别
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
                    //将地图移动到定位点
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                    //点击定位按钮 能够将地图的中心移动到定位点
                    mListener.onLocationChanged(aMapLocation);
                    //获取定位信息
                    StringBuffer buffer = new StringBuffer();
                    buffer.append(
                              aMapLocation.getCity() + ""
                            + aMapLocation.getDistrict() + ""
                            + aMapLocation.getStreet() + ""
                            + aMapLocation.getStreetNum());
                    //Toast.makeText(getApplicationContext(), buffer.toString(), Toast.LENGTH_LONG).show();
                    addressName=buffer.toString();
                    isFirstLoc = false;
                }
            } else {
                //显示错误信息ErrCode是错误码,errInfo是错误信息,详见错误码表。
//                Log.e("AmapError", "location Error, ErrCode:"
//                        + aMapLocation.getErrorCode() + ", errInfo:"
//                        + aMapLocation.getErrorInfo());
                Toast.makeText(getApplicationContext(), "定位失败", Toast.LENGTH_LONG).show();
            }

            showInUnderTextView(addressName);
        }
    }
    //获得地址后,在下边的textview中更改一下UI界面
    private void showInUnderTextView(String addressName) {
        tv_undermap.setText("已为您定位到“"+addressName+"”,我们将默认您的服务地址在该地点附近," +
                "并优先推荐该地点附近的客户给您。同意请点击“确认”,如需修改,请重新输入定位。");

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.confirm:


                break;
            case R.id.cancel:

                break;
            case R.id.iv_search:
                GeocodeSearched();
                break;
        }

    }
    //地理编码查找位置的回调
    private void GeocodeSearched() {
        String addressSearch = et_address_search.getText().toString().trim();
        // name表示地址,第二个参数表示查询城市,中文或者中文全拼,citycode、adcode
        GeocodeQuery query = new GeocodeQuery(addressSearch, "010");
        geocoderSearch.getFromLocationNameAsyn(query);


    }

    //逆地理编码的回调
    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {

        addressName = "";

        if (rCode == 1000) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {
                addressName = result.getRegeocodeAddress().getFormatAddress()
                        + "附近";
                //ToastUtil.showNormalShortToast(addressName);

            } else {
                addressName ="获取地址错误";
                ToastUtil.showNormalShortToast(addressName);
            }
        } else {
            addressName ="获取地址错误";
            ToastUtil.showNormalShortToast(addressName);
        }

        showInUnderTextView(addressName);
        aMap.clear();
        marker = new MarkerOptions().position(markerLatLng)
                .title("您选择的位置").snippet(addressName)
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));

        aMap.addMarker(marker).showInfoWindow();



    }
    //地理编码
    @Override
    public void onGeocodeSearched(GeocodeResult result, int rCode) {
        if (rCode == 1000) {
            if (result != null && result.getGeocodeAddressList() != null
                    && result.getGeocodeAddressList().size() > 0) {

                List<GeocodeAddress> geocodeAddressList = result.getGeocodeAddressList();
                LatLng[] latLngs=new LatLng[geocodeAddressList.size()];
                String[] descs=new String[geocodeAddressList.size()];
                for (int i=0;i<geocodeAddressList.size();i++) {
                    GeocodeAddress address = geocodeAddressList.get(i);
                    LatLonPoint latLonPoint = address.getLatLonPoint();
                    LatLng latLng = new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude());
                    String addressDesc = address.getFormatAddress();
                    latLngs[i]=latLng;
                    descs[i]=addressDesc;
                }
                aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(
                        latLngs[0], 18, 0, 30)));

                addMapMarkersBySearch(latLngs,descs);

            } else {
                ToastUtil.showNormalShortToast("网络不好,搜索失败!");
            }

        } else {
                ToastUtil.showNormalShortToast("网络不好,搜索失败!");
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值