Android开发中之手机定位(记录)

本篇博客主要记录一下如何进行手机定位到某一个城市之类的功能。当前,这里用到了百度地图的第三方地图解析API。

百度地图开放平台地址:http://lbsyun.baidu.com/index.php?title=androidsdk/guide/key

步骤如下:

1、运用Android自带的定位功能,来获取到当前设备处于的经度和纬度值。

2、通过百度地图的解析API,来获取到包含地址信息的Json字符串。

3、通过fastjson来解析json,获取到所在的城市,并显示到界面上。

具体实现如下:

1、定位方法类LocationUtil.java的代码如下:

/**
 * 定位的方法类
 */
public class LocationUtil {

    //百度地图申请的key
    public static String baiduKey = "TSg776uecpSG4xRHZvttYDe57u5au72q";

    public static String getLocation(Context mContext) {
        String locationProvider;
        //获取地理位置管理器
        LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providers = locationManager.getProviders(true);
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER;
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是Network
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else {
            Toast.makeText(mContext, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();
            return null;
        }
        //获取Location
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            return null;
        }
        Location location = locationManager.getLastKnownLocation(locationProvider);
        if (location != null) {
            //经度和纬度
            return showLocation(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
        }
        return null;
    }

    public static String showLocation(String wd, String jd) {
        String path = "http://api.map.baidu.com/geocoder?output=json&location=" + wd + "," + jd + "&key=" + baiduKey;
        String locationStr = ApiUtils.submitGetData(path);
        Log.e("path-------", locationStr);
        if (!locationStr.equals("")) {
            return locationStr;
        }
        return null;
    }
}

2、其中ApiUtils.submitGetData()方法是通过get方式来获取API数据。实现代码如下:

/**
 * 发送Get请求到服务器
 * @param strUrlPath:接口地址(带参数)
 * @return
 */
public static String submitGetData(String strUrlPath){
    String strResult = "";
    try {
        URL url = new URL(strUrlPath);
        HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
        httpURLConnection.setConnectTimeout(5000);
        httpURLConnection.setReadTimeout(5000);
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setUseCaches(true);
        //添加header头信息以便服务器辨别来自于哪个前端请求
        //设置请求体的类型是文本类型
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConnection.setRequestProperty("CLIENT-TYPE", "a");
        BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = in.readLine()) != null){
            buffer.append(line);
        }
        strResult = buffer.toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return strResult;
}

3、开启一个异步任务来执行定位操作,并处理相关显示。

class myLocationAsyncTask extends AsyncTask<Void, Void, Tb_LocationBaseResult> {


    @Override
    protected Tb_LocationBaseResult doInBackground(Void... voids) {
        String result = LocationUtil.getLocation(mContext);
        tb_locationBaseResult = null;
        if (result != null) {
            tb_locationBaseResult = JSON.parseObject(result, Tb_LocationBaseResult.class);
        }
        return tb_locationBaseResult;
    }

    @Override
    protected void onPostExecute(Tb_LocationBaseResult s) {
        if (s != null) {
            String city = s.get_result().get_addressComponent().get_city();
            tvCityLocation.setText("当前城市:" + city);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/lpCrazyBoy/article/details/81632796