高德地图之地理编码

来源:互联网 发布:嵌入式无人机软件 编辑:程序博客网 时间:2024/04/28 06:34

首先申明是地理编码呢?地理编码,又称为地址匹配,是从已知的地址描述到对应的经纬度坐标的转换过程。该功能适用于根据用户输入的地址确认用户具体位置的场景,常用于配送人员根据用户输入的具体地址找地点。既地理编码(地址转坐标)。
这里写图片描述
下面一步步来看怎么实现的:
1、继承 OnGeocodeSearchListener 监听。
2、构造 GeocodeSearch 对象,并设置监听。

geocoderSearch = new GeocodeSearch(this);geocoderSearch.setOnGeocodeSearchListener(this);

3、通过 GeocodeQuery(java.lang.String locationName, java.lang.String city) 设置查询参数,调用 GeocodeSearch 的 getFromLocationNameAsyn(GeocodeQuery geocodeQuery) 方法发起请求。

// name表示地址,第二个参数表示查询城市,中文或者中文全拼,citycode、adcode GeocodeQuery query = new GeocodeQuery(name, "010"); geocoderSearch.getFromLocationNameAsyn(query); 

4、通过回调接口 onGeocodeSearched 解析返回的结果。

说明:
1)可以在回调中解析result,获取坐标信息。
2)返回结果成功或者失败的响应码。1000为成功

//地理编码结果回调   @Overridepublic void onGeocodeSearched(GeocodeResult result, int rCode) {    dismissDialog();    if (rCode == 1000) {        if (result != null && result.getGeocodeAddressList() != null                && result.getGeocodeAddressList().size() > 0) {            GeocodeAddress address = result.getGeocodeAddressList().get(0);            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(                    AMapUtil.convertToLatLng(address.getLatLonPoint()), 15));            geoMarker.setPosition(AMapUtil.convertToLatLng(address                    .getLatLonPoint()));            addressName = "经纬度值:" + address.getLatLonPoint() + "\n位置描述:"                    + address.getFormatAddress();            ToastUtil.show(GeocoderActivity.this, addressName);        } else {            ToastUtil.show(GeocoderActivity.this, R.string.no_result);        }    } else {        ToastUtil.showerror(this, rCode);    }}

贴个具体实现类

/** * 地理编码 *  Created by dong.he on 2017-1-9 */public class GeocoderActivity extends Activity implements        OnGeocodeSearchListener, OnClickListener, LocationSource,        AMapLocationListener {    private ProgressDialog progDialog = null;    private GeocodeSearch geocoderSearch;    private String addressName;    private AMap aMap;    private MapView mapView;    private Marker geoMarker;    private EditText geoInput;    //定位    private LocationSource.OnLocationChangedListener mListener;    private AMapLocationClient mlocationClient;    private AMapLocationClientOption mLocationOption;    private Double myLat = 0.0, myLongt = 0.0;//我的当前位置的经纬度    private String cityCode = null;    private String currentCity = null;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.geocoder_activity);        /*         * 设置离线地图存储目录,在下载离线地图或初始化地图设置;         * 使用过程中可自行设置, 若自行设置了离线地图存储的路径,         * 则需要在离线地图下载和使用地图页面都进行路径设置         * */        //Demo中为了其他界面可以使用下载的离线地图,使用默认位置存储,屏蔽了自定义设置//        MapsInitializer.sdcardDir =OffLineMapUtils.getSdCacheDir(this);        mapView = (MapView) findViewById(R.id.map);        mapView.onCreate(savedInstanceState);// 此方法必须重写        init();    }    /**     * 初始化AMap对象     */    private void init() {        if (aMap == null) {            aMap = mapView.getMap();            geoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)                    .icon(BitmapDescriptorFactory                            .defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));            setUpLocation();        }        geoInput = (EditText) findViewById(R.id.input_edittext);        findViewById(R.id.btn_search).setOnClickListener(this);        geocoderSearch = new GeocodeSearch(this);        geocoderSearch.setOnGeocodeSearchListener(this);        progDialog = new ProgressDialog(this);    }    /**     * 方法必须重写     */    @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();    }    /**     * 显示进度条对话框     */    public void showDialog() {        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);        progDialog.setIndeterminate(false);        progDialog.setCancelable(true);        progDialog.setMessage("正在获取地址");        progDialog.show();    }    /**     * 隐藏进度条对话框     */    public void dismissDialog() {        if (progDialog != null) {            progDialog.dismiss();        }    }    /**     * 响应地理编码     */    public void getLatlon(final String name) {        showDialog();        GeocodeQuery query = new GeocodeQuery(name, cityCode);// 第一个参数表示地址,第二个参数表示查询城市,中文或者中文全拼,citycode、adcode,        geocoderSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求    }    /**     * 地理编码查询回调     */    @Override    public void onGeocodeSearched(GeocodeResult result, int rCode) {        dismissDialog();        if (rCode == AMapException.CODE_AMAP_SUCCESS) {            if (result != null && result.getGeocodeAddressList() != null                    && result.getGeocodeAddressList().size() > 0) {                GeocodeAddress address = result.getGeocodeAddressList().get(0);                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(                        AMapUtil.convertToLatLng(address.getLatLonPoint()), 15));                geoMarker.setPosition(AMapUtil.convertToLatLng(address                        .getLatLonPoint()));                addressName = "经纬度值:" + address.getLatLonPoint() + "\n位置描述:"                        + address.getFormatAddress();                ToastUtil.show(GeocoderActivity.this, addressName);            } else {                ToastUtil.show(GeocoderActivity.this, R.string.no_result);            }        } else {            ToastUtil.showerror(this, rCode);        }    }    /**     * 逆地理编码回调     */    @Override    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {    }    @Override    public void onClick(View v) {        switch (v.getId()) {            /**             * 响应地理编码按钮             */            case R.id.btn_search:                getLatlon(geoInput.getText().toString());                break;            default:                break;        }    }    /**     * 设置一些amap的属性     */    private void setUpLocation() {        aMap.setLocationSource(this);// 设置定位监听        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false        // 设置定位的类型为定位模式 ,可以由定位、跟随或地图根据面向方向旋转几种        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);    }    /**     * 定位成功后回调函数     */    @Override    public void onLocationChanged(AMapLocation amapLocation) {        if (mListener != null && amapLocation != null) {            if (amapLocation != null                    && amapLocation.getErrorCode() == 0) {                //定位成功回调信息,设置相关消息                amapLocation.getLocationType();//获取当前定位结果来源,如网络定位结果,详见定位类型表                myLat = amapLocation.getLatitude();//获取纬度                myLongt = 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();//省信息                currentCity = amapLocation.getCity();//城市信息                amapLocation.getDistrict();//城区信息                amapLocation.getStreet();//街道信息                amapLocation.getStreetNum();//街道门牌号信息                cityCode = amapLocation.getCityCode();//城市编码                amapLocation.getAdCode();//地区编码                TextView textView = (TextView) findViewById(R.id.city_detail);                textView.setText(amapLocation.getCity() + "=" + amapLocation.getDistrict() + "==" + amapLocation.getStreetNum());                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点            } else {                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();                Log.e("AmapErr", errText);            }        }    }    /**     * 激活定位     */    @Override    public void activate(LocationSource.OnLocationChangedListener listener) {        mListener = listener;        if (mlocationClient == null) {            mlocationClient = new AMapLocationClient(this);            mLocationOption = new AMapLocationClientOption();            //设置定位监听            mlocationClient.setLocationListener(this);            //设置为高精度定位模式            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);            //设置定位参数            mlocationClient.setLocationOption(mLocationOption);            // 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗,            // 注意设置合适的定位时间的间隔(最小间隔支持为2000ms),并且在合适时间调用stopLocation()方法来取消定位请求            // 在定位结束后,在合适的生命周期调用onDestroy()方法            // 在单次定位情况下,定位无论成功与否,都无需调用stopLocation()方法移除请求,定位sdk内部会移除            mlocationClient.startLocation();        }    }    /**     * 停止定位     */    @Override    public void deactivate() {        mListener = null;        if (mlocationClient != null) {            mlocationClient.stopLocation();            mlocationClient.onDestroy();        }        mlocationClient = null;    }}

地理编码其实就是这么简单。下一篇会继续讲逆地理编码。

1 0
原创粉丝点击