Android进阶篇-百度地图获取地理信息

简介: Android进阶篇-百度地图获取地理信息 Android中获取用户的地理信息的方式有很多种,各有各得优点和缺点。 这里主要介绍的方法是通过调用百度提供的地图API获取用户的地理位置信息。


Android进阶篇-百度地图获取地理信息

Android中获取用户的地理信息的方式有很多种,各有各得优点和缺点。

这里主要介绍的方法是通过调用百度提供的地图API获取用户的地理位置信息。

首要不可缺少的还是百度提供的标准Application类

复制代码
public class BMapApiApplication extends Application {
    
    public static BMapApiApplication mDemoApp;
    
    public static float mDensity;
    
    //百度MapAPI的管理类
    public BMapManager mBMapMan = null;
    
    // 授权Key
    // TODO: 请输入您的Key,
    // 申请地址:http://dev.baidu.com/wiki/static/imap/key/
    public String mStrKey = "F9FBF9FAA9BA37C0C6085BD280723A659EC51B20";
    public boolean m_bKeyRight = true;    // 授权Key正确,验证通过
    
    // 常用事件监听,用来处理通常的网络错误,授权验证错误等
    public static class MyGeneralListener implements MKGeneralListener {
        @Override
        public void onGetNetworkState(int iError) {
            Toast.makeText(BMapApiApplication.mDemoApp.getApplicationContext(), "您的网络出错啦!",
                    Toast.LENGTH_LONG).show();
        }

        @Override
        public void onGetPermissionState(int iError) {
            if (iError ==  MKEvent.ERROR_PERMISSION_DENIED) {
                // 授权Key错误:
                Toast.makeText(BMapApiApplication.mDemoApp.getApplicationContext(), 
                        "请在BMapApiDemoApp.java文件输入正确的授权Key!",
                        Toast.LENGTH_LONG).show();
                BMapApiApplication.mDemoApp.m_bKeyRight = false;
            }
        }
        
    }
    
    @Override
    public void onCreate() {
        mDemoApp = this;
        mBMapMan = new BMapManager(this);
        mBMapMan.init(this.mStrKey, new MyGeneralListener());
        
        mDensity = getResources().getDisplayMetrics().density;
        
        super.onCreate();
    }
    
    @Override
    //建议在您app的退出之前调用mapadpi的destroy()函数,避免重复初始化带来的时间消耗
    public void onTerminate() {
        // TODO Auto-generated method stub
        if (mBMapMan != null) {
            mBMapMan.destroy();
            mBMapMan = null;
        }
        super.onTerminate();
    }

}
复制代码

然后是通过注册百度地图调用相应的接口获取经纬度获取相应的信息

复制代码
/** Called when the activity is first created. */
    /** 上下文 */
    private BMapApiApplication mApplication;
    /** 定义搜索服务类 */
    private MKSearch mMKSearch;
    
    /** 记录当前经纬度的MAP*/
    private HashMap<String, Double> mCurLocation = new HashMap<String, Double>();
    //城市名
    private String cityName;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mApplication = (BMapApiApplication) this.getApplication();
        if (mApplication.mBMapMan == null) {
            mApplication.mBMapMan = new BMapManager(getApplication());
            mApplication.mBMapMan.init(mApplication.mStrKey,
                    new BMapApiApplication.MyGeneralListener());
        }
        
        /** 初始化MKSearch */
        mMKSearch = new MKSearch();
        mMKSearch.init(mApplication.mBMapMan, new MySearchListener());
    }
    
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        this.registerLocationListener();
    }

    private void registerLocationListener() {
        mApplication.mBMapMan.getLocationManager().requestLocationUpdates(
                mLocationListener);
        if (mApplication.mBMapMan != null) {
            /** 开启百度地图API */
            mApplication.mBMapMan.start();
        }
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        this.unRegisterLocationListener();
    }

    private void unRegisterLocationListener() {
        mApplication.mBMapMan.getLocationManager().removeUpdates(
                mLocationListener);
        if (mApplication.mBMapMan != null) {
            /** 终止百度地图API */
            mApplication.mBMapMan.stop();
        }
    }

    @Override
    protected void onDestroy() {
        if (mApplication.mBMapMan != null) {
            /** 程序退出前需调用此方法 */
            mApplication.mBMapMan.destroy();
            mApplication.mBMapMan = null;
        }
        super.onDestroy();
    }

    /** 注册定位事件 */
    private LocationListener mLocationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            if (location != null) {
                try {
                    int longitude = (int) (1000000 * location.getLongitude());
                    int latitude = (int) (1000000 * location.getLatitude());

                    /** 保存当前经纬度 */
                    mCurLocation.put("longitude", location.getLongitude());
                    mCurLocation.put("latitude", location.getLatitude());

                    GeoPoint point = new GeoPoint(latitude, longitude);
                    /** 查询该经纬度值所对应的地址位置信息 */
                    Weather_WelcomeActivity.this.mMKSearch
                            .reverseGeocode(new GeoPoint(latitude, longitude));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    /** 内部类实现MKSearchListener接口,用于实现异步搜索服务 */
    private class MySearchListener implements MKSearchListener {
        @Override
        public void onGetAddrResult(MKAddrInfo result, int iError) {
            if( iError != 0 || result == null){
                Toast.makeText(Weather_WelcomeActivity.this, "获取地理信息失败", Toast.LENGTH_LONG).show();
            }else {
                Log.info("json", "result= " + result);
                cityName =result.addressComponents.city;
                Bundle bundle = new Bundle();
                bundle.putString("cityName", cityName.substring(0, cityName.lastIndexOf("")));
                Intent intent = new Intent(Weather_WelcomeActivity.this,Weather_MainActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                Weather_WelcomeActivity.this.finish();
            }
        }

        @Override
        public void onGetDrivingRouteResult(MKDrivingRouteResult result,
                int iError) {
        }

        @Override
        public void onGetPoiResult(MKPoiResult result, int type, int iError) {
        }

        @Override
        public void onGetTransitRouteResult(MKTransitRouteResult result,
                int iError) {
        }

        @Override
        public void onGetWalkingRouteResult(MKWalkingRouteResult result,
                int iError) {
        }
    }
复制代码

其他方式获取当前的城市名:

复制代码
/**
     * 抓取当前的城市信息
     * 
     * @return String 城市名
     */
    public String getCurrentCityName(){
        String city = "";
        TelephonyManager telManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        GsmCellLocation glc = (GsmCellLocation) telManager.getCellLocation();
        
        if (glc != null){
            int cid = glc.getCid(); // value 基站ID号
            int lac = glc.getLac();// 写入区域代码
            String strOperator = telManager.getNetworkOperator();
            int mcc = Integer.valueOf(strOperator.substring(0, 3));// 写入当前城市代码
            int mnc = Integer.valueOf(strOperator.substring(3, 5));// 写入网络代码
            String getNumber = "";
            getNumber += ("cid:" + cid + "\n");
            getNumber += ("cid:" + lac + "\n");
            getNumber += ("cid:" + mcc + "\n");
            getNumber += ("cid:" + mnc + "\n");
            DefaultHttpClient client = new DefaultHttpClient();
            BasicHttpParams params = new BasicHttpParams();
            HttpConnectionParams.setSoTimeout(params, 20000);
            HttpPost post = new HttpPost("http://www.google.com/loc/json");
            
            try{
                JSONObject jObject = new JSONObject();
                jObject.put("version", "1.1.0");
                jObject.put("host", "maps.google.com");
                jObject.put("request_address", true);
                if (mcc == 460)
                    jObject.put("address_language", "zh_CN");
                else
                    jObject.put("address_language", "en_US");

                JSONArray jArray = new JSONArray();
                JSONObject jData = new JSONObject();
                jData.put("cell_id", cid);
                jData.put("location_area_code", lac);
                jData.put("mobile_country_code", mcc);
                jData.put("mobile_network_code", mnc);
                jArray.put(jData);
                jObject.put("cell_towers", jArray);
                StringEntity se = new StringEntity(jObject.toString());
                post.setEntity(se);

                HttpResponse resp = client.execute(post);
                BufferedReader br = null;
                if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                    br = new BufferedReader(new InputStreamReader(resp
                            .getEntity().getContent()));
                    StringBuffer sb = new StringBuffer();

                    String result = br.readLine();
                    while (result != null){
                        sb.append(getNumber);
                        sb.append(result);
                        result = br.readLine();
                    }
                    String s = sb.toString();
                    s = s.substring(s.indexOf("{"));
                    JSONObject jo = new JSONObject(s);
                    JSONObject arr = jo.getJSONObject("location");
                    JSONObject address = arr.getJSONObject("address");
                    city = address.getString("city");
                }
            }
            catch (JSONException e){
                e.printStackTrace();
            }
            catch (UnsupportedEncodingException e){
                e.printStackTrace();
            }
            catch (ClientProtocolException e){
                e.printStackTrace();
            }
            catch (IOException e){
                e.printStackTrace();
            }
            finally{
                post.abort();
                client = null;
            }
        }
        return city;
    }
复制代码

 加入这两个权限:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
。!

Android进阶篇-百度地图获取地理信息

Android中获取用户的地理信息的方式有很多种,各有各得优点和缺点。

这里主要介绍的方法是通过调用百度提供的地图API获取用户的地理位置信息。

首要不可缺少的还是百度提供的标准Application类

复制代码
public class BMapApiApplication extends Application {
    
    public static BMapApiApplication mDemoApp;
    
    public static float mDensity;
    
    //百度MapAPI的管理类
    public BMapManager mBMapMan = null;
    
    // 授权Key
    // TODO: 请输入您的Key,
    // 申请地址:http://dev.baidu.com/wiki/static/imap/key/
    public String mStrKey = "F9FBF9FAA9BA37C0C6085BD280723A659EC51B20";
    public boolean m_bKeyRight = true;    // 授权Key正确,验证通过
    
    // 常用事件监听,用来处理通常的网络错误,授权验证错误等
    public static class MyGeneralListener implements MKGeneralListener {
        @Override
        public void onGetNetworkState(int iError) {
            Toast.makeText(BMapApiApplication.mDemoApp.getApplicationContext(), "您的网络出错啦!",
                    Toast.LENGTH_LONG).show();
        }

        @Override
        public void onGetPermissionState(int iError) {
            if (iError ==  MKEvent.ERROR_PERMISSION_DENIED) {
                // 授权Key错误:
                Toast.makeText(BMapApiApplication.mDemoApp.getApplicationContext(), 
                        "请在BMapApiDemoApp.java文件输入正确的授权Key!",
                        Toast.LENGTH_LONG).show();
                BMapApiApplication.mDemoApp.m_bKeyRight = false;
            }
        }
        
    }
    
    @Override
    public void onCreate() {
        mDemoApp = this;
        mBMapMan = new BMapManager(this);
        mBMapMan.init(this.mStrKey, new MyGeneralListener());
        
        mDensity = getResources().getDisplayMetrics().density;
        
        super.onCreate();
    }
    
    @Override
    //建议在您app的退出之前调用mapadpi的destroy()函数,避免重复初始化带来的时间消耗
    public void onTerminate() {
        // TODO Auto-generated method stub
        if (mBMapMan != null) {
            mBMapMan.destroy();
            mBMapMan = null;
        }
        super.onTerminate();
    }

}
复制代码

然后是通过注册百度地图调用相应的接口获取经纬度获取相应的信息

复制代码
/** Called when the activity is first created. */
    /** 上下文 */
    private BMapApiApplication mApplication;
    /** 定义搜索服务类 */
    private MKSearch mMKSearch;
    
    /** 记录当前经纬度的MAP*/
    private HashMap<String, Double> mCurLocation = new HashMap<String, Double>();
    //城市名
    private String cityName;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mApplication = (BMapApiApplication) this.getApplication();
        if (mApplication.mBMapMan == null) {
            mApplication.mBMapMan = new BMapManager(getApplication());
            mApplication.mBMapMan.init(mApplication.mStrKey,
                    new BMapApiApplication.MyGeneralListener());
        }
        
        /** 初始化MKSearch */
        mMKSearch = new MKSearch();
        mMKSearch.init(mApplication.mBMapMan, new MySearchListener());
    }
    
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        this.registerLocationListener();
    }

    private void registerLocationListener() {
        mApplication.mBMapMan.getLocationManager().requestLocationUpdates(
                mLocationListener);
        if (mApplication.mBMapMan != null) {
            /** 开启百度地图API */
            mApplication.mBMapMan.start();
        }
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        this.unRegisterLocationListener();
    }

    private void unRegisterLocationListener() {
        mApplication.mBMapMan.getLocationManager().removeUpdates(
                mLocationListener);
        if (mApplication.mBMapMan != null) {
            /** 终止百度地图API */
            mApplication.mBMapMan.stop();
        }
    }

    @Override
    protected void onDestroy() {
        if (mApplication.mBMapMan != null) {
            /** 程序退出前需调用此方法 */
            mApplication.mBMapMan.destroy();
            mApplication.mBMapMan = null;
        }
        super.onDestroy();
    }

    /** 注册定位事件 */
    private LocationListener mLocationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            if (location != null) {
                try {
                    int longitude = (int) (1000000 * location.getLongitude());
                    int latitude = (int) (1000000 * location.getLatitude());

                    /** 保存当前经纬度 */
                    mCurLocation.put("longitude", location.getLongitude());
                    mCurLocation.put("latitude", location.getLatitude());

                    GeoPoint point = new GeoPoint(latitude, longitude);
                    /** 查询该经纬度值所对应的地址位置信息 */
                    Weather_WelcomeActivity.this.mMKSearch
                            .reverseGeocode(new GeoPoint(latitude, longitude));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    /** 内部类实现MKSearchListener接口,用于实现异步搜索服务 */
    private class MySearchListener implements MKSearchListener {
        @Override
        public void onGetAddrResult(MKAddrInfo result, int iError) {
            if( iError != 0 || result == null){
                Toast.makeText(Weather_WelcomeActivity.this, "获取地理信息失败", Toast.LENGTH_LONG).show();
            }else {
                Log.info("json", "result= " + result);
                cityName =result.addressComponents.city;
                Bundle bundle = new Bundle();
                bundle.putString("cityName", cityName.substring(0, cityName.lastIndexOf("")));
                Intent intent = new Intent(Weather_WelcomeActivity.this,Weather_MainActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                Weather_WelcomeActivity.this.finish();
            }
        }

        @Override
        public void onGetDrivingRouteResult(MKDrivingRouteResult result,
                int iError) {
        }

        @Override
        public void onGetPoiResult(MKPoiResult result, int type, int iError) {
        }

        @Override
        public void onGetTransitRouteResult(MKTransitRouteResult result,
                int iError) {
        }

        @Override
        public void onGetWalkingRouteResult(MKWalkingRouteResult result,
                int iError) {
        }
    }
复制代码

其他方式获取当前的城市名:

复制代码
/**
     * 抓取当前的城市信息
     * 
     * @return String 城市名
     */
    public String getCurrentCityName(){
        String city = "";
        TelephonyManager telManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        GsmCellLocation glc = (GsmCellLocation) telManager.getCellLocation();
        
        if (glc != null){
            int cid = glc.getCid(); // value 基站ID号
            int lac = glc.getLac();// 写入区域代码
            String strOperator = telManager.getNetworkOperator();
            int mcc = Integer.valueOf(strOperator.substring(0, 3));// 写入当前城市代码
            int mnc = Integer.valueOf(strOperator.substring(3, 5));// 写入网络代码
            String getNumber = "";
            getNumber += ("cid:" + cid + "\n");
            getNumber += ("cid:" + lac + "\n");
            getNumber += ("cid:" + mcc + "\n");
            getNumber += ("cid:" + mnc + "\n");
            DefaultHttpClient client = new DefaultHttpClient();
            BasicHttpParams params = new BasicHttpParams();
            HttpConnectionParams.setSoTimeout(params, 20000);
            HttpPost post = new HttpPost("http://www.google.com/loc/json");
            
            try{
                JSONObject jObject = new JSONObject();
                jObject.put("version", "1.1.0");
                jObject.put("host", "maps.google.com");
                jObject.put("request_address", true);
                if (mcc == 460)
                    jObject.put("address_language", "zh_CN");
                else
                    jObject.put("address_language", "en_US");

                JSONArray jArray = new JSONArray();
                JSONObject jData = new JSONObject();
                jData.put("cell_id", cid);
                jData.put("location_area_code", lac);
                jData.put("mobile_country_code", mcc);
                jData.put("mobile_network_code", mnc);
                jArray.put(jData);
                jObject.put("cell_towers", jArray);
                StringEntity se = new StringEntity(jObject.toString());
                post.setEntity(se);

                HttpResponse resp = client.execute(post);
                BufferedReader br = null;
                if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                    br = new BufferedReader(new InputStreamReader(resp
                            .getEntity().getContent()));
                    StringBuffer sb = new StringBuffer();

                    String result = br.readLine();
                    while (result != null){
                        sb.append(getNumber);
                        sb.append(result);
                        result = br.readLine();
                    }
                    String s = sb.toString();
                    s = s.substring(s.indexOf("{"));
                    JSONObject jo = new JSONObject(s);
                    JSONObject arr = jo.getJSONObject("location");
                    JSONObject address = arr.getJSONObject("address");
                    city = address.getString("city");
                }
            }
            catch (JSONException e){
                e.printStackTrace();
            }
            catch (UnsupportedEncodingException e){
                e.printStackTrace();
            }
            catch (ClientProtocolException e){
                e.printStackTrace();
            }
            catch (IOException e){
                e.printStackTrace();
            }
            finally{
                post.abort();
                client = null;
            }
        }
        return city;
    }
复制代码

 加入这两个权限:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
相关文章
|
8月前
|
定位技术 API 开发工具
Android 按照步骤接入百度地图API,定位显示不了解决办法
Android 按照步骤接入百度地图API,定位显示不了解决办法
225 0
|
Java 定位技术 API
Android--百度地图密钥申请+环境配置(一)
版权声明:本文为博主原创文章,转载请标明出处。 https://blog.csdn.net/chaoyu168/article/details/51360593 简介 在使用百度地图SDK为您提供的各种LBS能力之前,您需要获取百度地图移动版的开发密钥,该密钥与您的百度账户相关联。
1313 0
|
设计模式 前端开发 调度
Android体系课之--Kotlin协程进阶篇-协程在Android组件中的使用(四)
1.协程通过将复杂性放入库来简化异步编程。程序的逻辑可以在协程中顺序地表达,而底层库会为我们解决其异步性。该库可以将用户代码的相关部分包装为回调、订阅相关事件、在不同线程(甚至不同机器!)上调度执行,而代码则保持如同顺序执行一样简单。 2.协程是一种并发设计模式,您可以在Android平台上使用它来简化异步执行的代码
|
设计模式 前端开发 Java
Android体系课之--Kotlin协程进阶篇-协程的异常处理机制以及suspend关键字(三)
协程通过将复杂性放入库来简化异步编程。程序的逻辑可以在协程中顺序地表达,而底层库会为我们解决其异步性。该库可以将用户代码的相关部分包装为回调、订阅相关事件、在不同线程(甚至不同机器!)上调度执行,而代码则保持如同顺序执行一样简单。
|
设计模式 前端开发 编译器
Android体系课之--Kotlin协程进阶篇-协程中关键知识点梳理(二)
笔者在写这篇文章之前,也白嫖了很多关于Kotlin协程的文章: 这里笔者将他们分为三种: 1.讲的内容很*浅*,没几句可能就结束了,看完就索然无味了 2.讲的内容很*深*,看到一半就开始晕乎乎了,然后可能还是手机好玩。。 3.内容比较*适中*,读者可以在里面获取到一些协程的基本信息,关键内容可能就浅尝辄止了,很难获取到核心知识点 > 知识的学习就像谈恋爱,不能一上来就想和对方深入了解,也不能聊得太浅,影响后续发展,得讲究循序渐进。 接下来笔者会根据由浅入深的方式,阶段性来讲解Kotlin协程相关知识点。读者可以根据自己的需求,选择对应的阶段文章
|
定位技术 API Android开发
Android Studio进行APP设计调用百度地图API接口隐藏百度地图的logo方法
Android Studio进行APP设计调用百度地图API接口隐藏百度地图的logo方法
315 0
Android Studio进行APP设计调用百度地图API接口隐藏百度地图的logo方法
|
定位技术 API Android开发
安卓百度地图显示地图上所有的点(Marker)
安卓百度地图显示地图上所有的点(Marker)
273 0
|
定位技术 Android开发
安卓百度地图点击回到当前位置
安卓百度地图点击回到当前位置
217 0
|
定位技术 API Android开发
安卓百度地图的所有覆盖物
安卓百度地图的所有覆盖物
96 0