高德地图精确查找与定位RegeocodeQuery与GeocodeQuery

2023-10-26

根据输入的字符串精确查找位置,用GeocodeQuery查找坐标,然后根据获取到的坐标,用RegeocodeQuery查询地址。例子中用了两个页面,一个是显示地址信息及定位的页面,另一个是搜索页面,点击搜索结果返回显示页面,显示信息并定位:

显示并定位的页面:


public class SaleMapActivity extends AppCompatActivity implements GeocodeSearch.OnGeocodeSearchListener {
    private static final String TAG = "SaleMapActivity";

    @BindView(R.id.iv_mapBack)
    ImageView ivMapBack;
    @BindView(R.id.afterSaleMap)
    MapView afterSaleMap;
    @BindView(R.id.iv_saleSear)
    ImageView ivSaleSear;
    @BindView(R.id.rl_sale_search)
    RelativeLayout rlSaleSearch;
    @BindView(R.id.tv_pointName)
    TextView tvPointName;
    @BindView(R.id.tv_distance)
    TextView tvDistance;
    @BindView(R.id.iv_location)
    ImageView ivLocation;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.ll_location)
    LinearLayout llLocation;
    @BindView(R.id.iv_phone)
    ImageView ivPhone;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.ll_phone)
    LinearLayout llPhone;
    @BindView(R.id.map_bottom)
    LinearLayout mapBottom;
    AMap aMap;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    private Marker geoMarker;
    private Marker regeoMarker;
    private Double lat;
    private Double lon;
    private String mCity = "";
    private String areaInfo="";
    private String adCode = "";
    Context mContext;
    private GeocodeSearch geocoderSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sale_map);
        ButterKnife.bind(this);
        afterSaleMap.onCreate(savedInstanceState);
        mContext = SaleMapActivity.this;
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        initAmap();
    }

    /**
     * * 初始化AMap对象
     */
    private void initAmap() {
        if (aMap == null) {
            aMap = afterSaleMap.getMap();
        }

        setUpMap();

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

    }

    private void setUpMap() {
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式,Battery_Saving为低功耗模式,Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息(默认返回地址信息)
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否强制刷新WIFI,默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false,不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
//        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);

        //启动定位
        mLocationClient.startLocation();

        //重新定位时移除红气泡,再重新初始化
        geoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
//        geoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
//                .icon(BitmapDescriptorFactory.fromResource(R.drawable.cur_position)));
//        regeoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
//                .icon(BitmapDescriptorFactory
//                        .defaultMarker(BitmapDescriptorFactory.HUE_RED)));
        regeoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_map_search)));
    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            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();//省信息
                    mCity = amapLocation.getCity();//城市信息
                    amapLocation.getDistrict();//城区信息
                    amapLocation.getStreet();//街道信息
                    amapLocation.getStreetNum();//街道门牌号信息
                    amapLocation.getCityCode();//城市编码
                    adCode = amapLocation.getAdCode();//地区编码
                    amapLocation.getAoiName();//获取当前定位点的AOI信息
                    lat = amapLocation.getLatitude();
                    lon = amapLocation.getLongitude();
                    areaInfo = amapLocation.getProvince()+" "+amapLocation.getCity() +" "+amapLocation.getDistrict();
                    Log.v("pcw", "lat : " + lat + " lon : " + lon+" adCode: "+adCode+","+areaInfo);
                    Log.v("pcw", "amapLocation="+amapLocation.toString());
//                    etEAddr.setText(amapLocation.getAoiName());
                    tvPointName.setText(amapLocation.getAoiName());
                    tvLocation.setText(amapLocation.getAddress());

                    // 设置当前地图显示为当前位置
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 16));
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions.position(new LatLng(lat, lon));
                    markerOptions.title("当前位置");
                    markerOptions.visible(true);
//                    BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.location_marker));
//                    BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.cur_position);
                    //设置当前位置的marker图标
                    ImageView imageView = new ImageView(SaleMapActivity.this);
                    imageView.setImageResource(R.drawable.cur_position);
                    BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromView(imageView);
                    markerOptions.icon(bitmapDescriptor);
                    aMap.addMarker(markerOptions);
//                    mLocationListener.onLocationChanged(amapLocation);

                } else {
                    //显示错误信息ErrCode是错误码,errInfo是错误信息,详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                    Toast.makeText(mContext,amapLocation.getErrorInfo(),Toast.LENGTH_LONG).show();
                }
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode,int resultCode,Intent data){
        LogUtil.d("SaleMapActivity","sdjflksdfjdlskf");
        if(requestCode == 1){
            if(resultCode == RESULT_OK){
                LogUtil.d("SaleMapActivity","onActivityResult===========");
                Bundle bundle = data.getBundleExtra("searAddr");
                GeocodeAddress address = bundle.getParcelable("addr");
                //根据传回来的地址坐标获取该地点的位置详细信息
                //通过 RegeocodeQuery(LatLonPoint point, float radius, java.lang.String latLonType) 设置查询参数
                RegeocodeQuery rQuery = new RegeocodeQuery(address.getLatLonPoint(),200,GeocodeSearch.AMAP);
                //调用 GeocodeSearch 的 getFromLocationAsyn(RegeocodeQuery regeocodeQuery) 方法发起请求。
                //通过回调接口 onRegeocodeSearched 解析返回的结果
                geocoderSearch.getFromLocationAsyn(rQuery);

            }
        }
    }

    @OnClick({R.id.iv_mapBack, R.id.rl_sale_search, R.id.ll_phone})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_mapBack:
                finish();
                break;
            case R.id.rl_sale_search:
                Intent searchIntent = new Intent(SaleMapActivity.this, SearchSaleActivity.class);
                startActivityForResult(searchIntent,1);
//                startActivity(searchIntent);
                break;
            case R.id.ll_phone:
                break;
        }
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        if(i== 1000){
            if(regeocodeResult != null && regeocodeResult.getRegeocodeAddress()!= null
                    && regeocodeResult.getRegeocodeAddress().getFormatAddress() != null){
                adCode = regeocodeResult.getRegeocodeAddress().getAdCode();
                LatLng latLng= convertToLatLng(regeocodeResult.getRegeocodeQuery().getPoint());
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
                regeoMarker.setPosition(latLng);
                RegeocodeAddress address = regeocodeResult.getRegeocodeAddress();
                List<PoiItem> poiItems = address.getPois();
                for(int j = 0;j<poiItems.size();j++){
                    PoiItem item = poiItems.get(j);
                    LogUtil.d(TAG,"Title="+item.getTitle()+",Distance="+item.getDistance()+",AdName="+item.getAdName()+",Tel"+item.getTel()
                            +",BusinessArea="+item.getBusinessArea()+",Snippet="+item.getSnippet()+",Direction"+item.getDirection()
                            +",TypeDes"+item.getTypeDes());
                }

                tvPointName.setText(poiItems.get(0).getTitle()+"附近");
                //我的当前位置与搜索到的位置的距离
                LatLng latLng1 = new LatLng(lat,lon);
                float distance = AMapUtils.calculateLineDistance(latLng1,regeoMarker.getPosition());
                tvDistance.setText(String.valueOf(distance));
                tvLocation.setText(address.getFormatAddress());
                tvPhone.setText(poiItems.get(0).getTel());
                Toast.makeText(mContext, "定位成功", Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(mContext, "定位失败", Toast.LENGTH_LONG).show();
            }
        }else{
            Toast.makeText(mContext, i, Toast.LENGTH_LONG).show();
        }
    }

    public LatLng convertToLatLng(LatLonPoint point){
        return new LatLng(point.getLatitude(),point.getLongitude());
    }

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

    }
}
2. 搜索页面:

public class SearchSaleActivity extends AppCompatActivity {
    private static final String TAG = "SearchSaleActivity";

    @BindView(R.id.salesearch_edit)
    TextField salesearchEdit;
    @BindView(R.id.tv_saleCancel)
    TextView tvSaleCancel;
    @BindView(R.id.lvResult)
    ListView lvResult;
    GeocodeSearch geocodeSearch;
    Context mContext;
    SearchMapAdapter adapter;
    List<GeocodeAddress> addrList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_sale);
        ButterKnife.bind(this);
        mContext = SearchSaleActivity.this;
        addrList = new ArrayList<GeocodeAddress>();
        //构造 GeocodeSearch 对象,并设置监听。
        geocodeSearch = new GeocodeSearch(mContext);
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
                //地理编码;根据地址获取坐标
                if(i == 1000){
                    LogUtil.d(TAG,"success");
                    if(geocodeResult != null && geocodeResult.getGeocodeAddressList() != null
                            && geocodeResult.getGeocodeAddressList().size() != 0){
                        LogUtil.d(TAG,""+geocodeResult.getGeocodeQuery().getLocationName());
                        addrList = geocodeResult.getGeocodeAddressList();
                        adapter = new SearchMapAdapter(mContext,addrList);
                        lvResult.setAdapter(adapter);

                    }
                }
            }
        });
        salesearchEdit.addTextChangedListener(new MyTextChangeListener());
        lvResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext,SaleMapActivity.class);
                Bundle bundle = new Bundle();
                bundle.putParcelable("addr",addrList.get(position));
                intent.putExtra("searAddr",bundle);
                setResult(RESULT_OK,intent);
                finish();
            }
        });
    }

    //文本框的改变监听
    class MyTextChangeListener implements TextWatcher{

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String newText = s.toString().trim();
            if(newText != null && !newText.equals("")){
                //通过 GeocodeQuery(java.lang.String locationName, java.lang.String city) 设置查询参数
                //name表示地址,第二个参数表示查询城市,中文或者中文全拼,citycode、adcode
                GeocodeQuery query = new GeocodeQuery(newText,"0532");
                //调用 GeocodeSearch 的 getFromLocationNameAsyn(GeocodeQuery geocodeQuery) 方法发起请求。
                //通过回调接口 onGeocodeSearched 解析返回的结果
                geocodeSearch.getFromLocationNameAsyn(query);
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    @OnClick(R.id.tv_saleCancel)
    public void onClick() {
    }
}
 



本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

高德地图精确查找与定位RegeocodeQuery与GeocodeQuery 的相关文章

随机推荐

  • Numpy:基础数据结构

    1 数组的基本属性 import numpy as np ar np array 1 2 3 4 5 6 7 print ar 输出数组 注意数组的格式 中括号 元素之间没有逗号 和列表区分 print ar ndim 输出数组维度的个数
  • Python @函数装饰器及用法(超级详细)转

    Python 内置的 3 种函数装饰器 分别是 staticmethod classmethod 和 property 其中 staticmethod classmethod 和 property 都是 Python 的内置函数 那么 我们
  • layui子弹框调用父弹框方法

    var thisFrame parent window document getElementById LAY layuiStampDuty1 getElementsByTagName iframe 0 id 获取父级弹框id值 var d
  • 【20220412】文献翻译4:交互中的手势和语言概述

    Gesture and speech in interaction An overview 1 简介 2 什么是共同语言 同声传译 手势 2 1 用手比划 2 2 用头做动作 3 语音和手势是交互的 3 1 交际环境中的手势 3 2 传递意
  • 双向链表

    双向就意味着对于每一个元素 都有两个方向的指向 因此从以下几个方面阐述双向链表 重要方法分析 全部代码 一 重要方法分析 这里的链表实现了我博客中的接口 ILinkedList 与结点 LinkedNode 具体的博客地址 http blo
  • 【Linux】VIM使用

    第一节 Vim常用操作 Vim没有菜单 只有命令 Vim的工作模式有三种 第一种 命令模式 vi vim 文件名 进入命令模式 不可以输入文字 只能识别命令 插入命令 a 在光标所在字符后插入 i 在光标所在字符前插入 o 在光标下插入新行
  • Vue基础精讲 —— Vue的组件之组件的定义、继承、自定义双向绑定、高级属性

    Vue组件基础定义 import Vue from vue const compoent props active type Boolean required true validator value return typeof value
  • UE4-蓝图基础:TimeLine

    一 概念 1 TimeLine 在一定时间内不断执行的一个蓝图节点 2 添加一个空白节点 函数讲解 Play 事件驱动 执行此事件时调用 Play from Start 从头开始执行事件 lt 事件在执行过程中未执行完毕 某一条件改变 事件
  • 回路电感详细介绍(环路电感)

    相比于硬件工程师 PCB工程师对环路电感更敏感 因为环路电感和走线强相关 不管是信号完整性还是电源完整性都涉及到这个概念 一旦电路结构确定 环路电感也随之确定 如果环路电感初期评估失误将会给后期改版带来巨大风险 更多资料请关注公众号 工程师
  • 操作系统 java模拟主存储器空间的分配和回收

    文章目录 实验原理 算法流程图 代码 结果 实验原理 模拟在可变分区管理方式下采用最先适应算法实现主存分配和回收 1 可变分区方式是按作业需要的主存空间大小来分割分区的 当要装入一个作业时 根据作业需要的主存量查看是否有足够的空闲空间 若有
  • 创建第一个Qt Widget项目

    创建第一个Qt Widget项目步骤 1 选择文件 Ctrl n 2 新建文件或项目 3 Qt Widget Application 4 输入项目名称FirstApplication 选择存储的位置 5 选择构建套件Desktop Qt Q
  • numpy一维数组永远为列向量

    import numpy as np a np array 1 3 4 5 print a shape a np transpose a print a shape print a a np ravel a print a shape pr
  • 静态分析简介

    一 程序静态分析简介 Program Static Analysis 程序静态分析简介 Program Static Analysis 是指在不运行代码的方式下 通过词法分析 语法分析 控制流 数据流分析等技术对程序代码进行扫描 验证代码是
  • 【mysql安装报错(已解决)】ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: YES)

    1 说在开头 我的 mysql 版本是 8 0 27 的 安装的时候 感觉每一步都没有错 但是就是不行 到连接本地数据库时 发现一直连不上 搞了好久 一直报下面的错 ERROR 1045 28000 Access denied for us
  • 一文带你聊聊MYSQL的锁和MVCC

    如果你觉得内容对你有帮助的话 不如给个赞 鼓励一下更新 本文内容总结自极客时间 MySQL实战45讲 专栏 LBCC 单版本控制 锁 基于锁的并发控制 这种方案比较简单粗暴 就是一个事务去读取一条数据的时候 就上锁 不允许其他事务来操作 当
  • 【Python自动化】生成带装饰图形的渐变背景文字封面

    Python自动化专栏 利用文字生成固定比例且带有装饰图形的封面 文章目录 一 背景介绍 二 功能介绍 效果预览 功能清单 三 过程拆解 1 渐变背景层 2 装饰图形层 3 半透明遮罩层 4 文字层 四 完整代码 参考文档 一 背景介绍 在
  • echarts地图map下钻到镇街、KMZ文件转GeoJson、合成自定义区域

    echarts 地图map下钻到镇街 KMZ文件转GeoJson 合成自定义区域 我们可以通过 http datav aliyun com tools atlas 阿里旗下的高德地图提供的api 可以获取到中国各个省份 区级 县级的json
  • NAT技术的主要实现方式及其对网络应用程序的使用影响

    网络地址转换 NAT 是接入广域网 WLAN 的一种技术 能够将私有 保留 地址转化为合法的IP地址 它被广泛应用于各种类型Internet接入方式和各种类型的网络中 NAT的实现方式有三种 静态转换 动态转换和端口多路复用 静态转换设置起
  • Linux审计与日志安全加固

    审计和日志服务配置 auditctl 审计数据配置 日志文件最大参数 在储存策略 etc audit audit conf 中配置max log file
  • 高德地图精确查找与定位RegeocodeQuery与GeocodeQuery

    根据输入的字符串精确查找位置 用GeocodeQuery查找坐标 然后根据获取到的坐标 用RegeocodeQuery查询地址 例子中用了两个页面 一个是显示地址信息及定位的页面 另一个是搜索页面 点击搜索结果返回显示页面 显示信息并定位