您的位置:首页 > 移动开发 > Android开发

android定位并获取城市

2016-01-05 11:26 495 查看
在项目中需要定位当前用户所在城市,然后根据不同城市返回不同的数据。一般来说,定位有两种方式,1、用第三方的定位sdk,如百度定位;2、用android自带的sdk中的api定位。

一、用百度SDK定位。这个具体操作见百度开发者平台。

二、用android自带的SDK定位。一般情况下,获取经纬度是很简单,再根据经纬度获取城市,这个获取城市也有多种方法。

定位获取经纬度:

private Location getLocation() {
//获取位置管理服务

//查找服务信息
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE); //定位精度: 最高
criteria.setAltitudeRequired(false); //海拔信息:不需要
criteria.setBearingRequired(false); //方位信息: 不需要
criteria.setCostAllowed(true);  //是否允许付费
criteria.setPowerRequirement(Criteria.POWER_LOW); //耗电量: 低功耗
//        String provider = myLocationManager.getBestProvider(criteria, true); //获取GPS信息
//        myLocationManager.requestLocationUpdates(provider,2000,5,locationListener);
//        Log.e("provider", provider);
//        List<String> list = myLocationManager.getAllProviders();
//        Log.e("provider", list.toString());
//
Location gpsLocation = null;
Location netLocation = null;
myLocationManager.addGpsStatusListener(myListener);
if (netWorkIsOpen()) {
//2000代表每2000毫秒更新一次,5代表每5秒更新一次
myLocationManager.requestLocationUpdates("network", 2000, 5, locationListener);
netLocation = myLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}

if (gpsIsOpen()) {
myLocationManager.requestLocationUpdates("gps", 2000, 5, locationListener);
gpsLocation = myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}

if (gpsLocation == null && netLocation == null) {
return null;
}
if (gpsLocation != null && netLocation != null) {
if (gpsLocation.getTime() < netLocation.getTime()) {
gpsLocation = null;
return netLocation;
} else {
netLocation = null;
return gpsLocation;
}
}
if (gpsLocation == null) {
return netLocation;
} else {
return gpsLocation;
}
}

定位主要有两种方式,GPS和NetWork。以上就是判断哪种方式可用就用哪个。

private boolean gpsIsOpen() {
boolean isOpen = true;
if (!myLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {//没有开启GPS
isOpen = false;
}
return isOpen;
}

private boolean netWorkIsOpen() {
boolean netIsOpen = true;
if (!myLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {//没有开启网络定位
netIsOpen = false;
}
return netIsOpen;
}

自定义LocationListener

//监听GPS位置改变后得到新的经纬度
private LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.e("location", location.toString() + "....");
// TODO Auto-generated method stub
if (location != null) {
//获取国家,省份,城市的名称
Log.e("location", location.toString());
//                List<Address> m_list = getAddress(location);
new MyAsyncExtue().execute(location);
//                Log.e("str", m_list.toString());
//                String city = "";
////                if (m_list != null && m_list.size() > 0) {
////                    city = m_list.get(0).getLocality();//获取城市
////                }
//                city = m_list;
//                show_GPS.setText("location:" + m_list.toString() + "\n" + "城市:" + city + "\n精度:" + location.getLongitude() + "\n纬度:" + location.getLatitude() + "\n定位方式:" + location.getProvider());
} else {
show_GPS.setText("获取不到数据");
}
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

};

其中的Location类就是我们需要获取到的位置信息,可以从中得到经纬度。

根据经纬度获取当前城市名的几种方式如下:(获取城市名需要网络连接,不管是百度定位的SDK,还是我们后面介绍的获取方式)

1.通过服务获取城市名(google或者baidu)

百度:http://api.map.baidu.com/geocoder?output=json&location=23.131427,113.379763&ak=esNPFDwwsXWtsQfw4NMNmur1

google:http://maps.google.com/maps/api/geocode/json?latlng=%2023.131427,113.379763&language=zh-CN&sensor=true

private class MyAsyncExtue extends AsyncTask<Location, Void, String> {

@Override
protected String doInBackground(Location... params) {
HttpClient client = new DefaultHttpClient();
StringBuilder stringBuilder = new StringBuilder();
HttpGet httpGet = new HttpGet("http://api.map.baidu.com/geocoder?output=json&location=23.131427,113.379763&ak=esNPFDwwsXWtsQfw4NMNmur1");
try {
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String b;
while ((b = bufferedReader.readLine()) != null) {
stringBuilder.append(b + "\n");
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}

@Override
protected void onPostExecute(String m_list) {
super.onPostExecute(m_list);
Log.e("str", m_list.toString());
String city = "";
//                if (m_list != null && m_list.size() > 0) {
//                    city = m_list.get(0).getLocality();//获取城市
//                }
city = m_list;
show_GPS.setText("城市:" + city);
}
}

这个获取到的city是json串,我只是测试是否可行,所以没有解析。

直接用http请求这连接,就会一json的形式返回当前的位置信息。不过google的服务在大陆依旧是不可用的。

2.用andorid的api获取城市。

// 获取地址信息
private List<Address> getAddress(Location location) {
List<Address> result = null;
try {
if (location != null) {
Geocoder gc = new Geocoder(this, Locale.getDefault());
result = gc.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

getFromLocation这个方法是耗时的,不要放在主线程中。

经测试,以上方法都是可行的。

测试结果截图如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息