实现的功能:先获取本地的经纬度,再根据经纬度,请求googleapis来解析地理位置名称。
下面的例子,能够跑起来,亲测。
多说无益,看码。
首先搞一个布局,其实就是一个textView,一个button,点击button后,在textview展示地理位置信息。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:id="@+id/tv_location_show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <Button android:id="@+id/btn_show_location" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="获取当前位置" > </Button> </RelativeLayout>
为了方便,我直接把获取地理位置、经纬度解析,都放到MainActivity里面了。(其实就是懒,这样不好,还是该做什么的类去做什么,应该分开放的)
package com.example.getlocation; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.Manifest; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private LocationManager locationManager;// 位置服务 private Location location;// 位置 private Button btn_show;// 按钮 private TextView tv_show;// 展示地理位置 public static final int SHOW_LOCATION = 0; private String lastKnowLoc; //监听地理位置变化,地理位置变化时,能够重置location LocationListener locationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { tv_show.setText("更新失败失败"); } @Override public void onLocationChanged(Location loc) { if (loc != null) { location = loc; showLocation(location); } } }; //这个不用说了,主要是初始化页面控件,并且设置按钮监听 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init();// 关联控件,初始化按钮、展示框 tv_show.setText("地理位置");// 设置默认的位置展示,也就是没有点击按钮时的展示 lastKnowLoc = "中国"; // 点击按钮时去初始化一次当前位置 btn_show.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { locationInit();// 调用位置初始化方法 } }); } //这个就是地理位置初始化,主要通过调用其他方法获取经纬度,并设置到location public void locationInit() { try { // 获取系统服务 locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); // 判断GPS是否可以获取地理位置,如果可以,展示位置, // 如果GPS不行,再判断network,还是获取不到,那就报错 if (locationInitByGPS() || locationInitByNETWORK()) { // 上面两个只是获取经纬度的,获取经纬度location后,再去调用谷歌解析来获取地理位置名称 showLocation(location); } else { tv_show.setText("获取地理位置失败,上次的地理位置为:" + lastKnowLoc); } } catch (Exception e) { tv_show.setText("获取地理位置失败,上次的地理位置为:" + lastKnowLoc); } } // GPS去获取location经纬度 public boolean locationInitByGPS() { // 没有GPS,直接返回 if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { return false; } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener); location = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { return true;//设置location成功,返回true } else { return false; } } // network去获取location经纬度 public boolean locationInitByNETWORK() { // 没有NETWORK,直接返回 if (!locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { return false; } locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener); location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { return true; } else { return false; } } //控件初始化 private void init() { btn_show = (Button) findViewById(R.id.btn_show_location); tv_show = (TextView) findViewById(R.id.tv_location_show); } //这是根据经纬度,向谷歌的API解析发网络请求,然后获取response,这里超时时间不要太短,否则来不及返回位置信息,直接失败了 private void showLocation(final Location loc) { new Thread(new Runnable() { @Override public void run() { try { // 去谷歌的地理位置获取中去解析经纬度对应的地理位置 StringBuilder url = new StringBuilder(); url.append("http://maps.googleapis.com/maps/api/geocode/json?latlng="); url.append(loc.getLatitude()).append(","); url.append(loc.getLongitude()); url.append("&sensor=false"); // 通过HttpClient去执行HttpGet HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url.toString()); httpGet.addHeader("Accept-Language", "zh-CN"); HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { HttpEntity entity = httpResponse.getEntity(); String response = EntityUtils.toString(entity, "utf-8"); JSONObject jsonObject = new JSONObject(response); JSONArray resultArray = jsonObject .getJSONArray("results"); if (resultArray.length() > 0) { JSONObject subObject = resultArray.getJSONObject(0); String address = subObject .getString("formatted_address"); Message message = new Message(); message.what = SHOW_LOCATION; message.obj = address; lastKnowLoc = address; handler.sendMessage(message); } } else { Message message = new Message(); message.what = SHOW_LOCATION; message.obj = "获取地理位置失败,上次的地理位置为:" + lastKnowLoc; handler.sendMessage(message); } } catch (Exception e) { Message message = new Message(); message.what = SHOW_LOCATION; message.obj = "获取地理位置失败,上次的地理位置为:" + lastKnowLoc; handler.sendMessage(message); e.printStackTrace(); } } }).start(); } //就是展示下获取到的地理位置 private Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case SHOW_LOCATION: String currentPosition = (String) msg.obj; tv_show.setText(currentPosition); break; default: break; } } }; }
上面基本就做好了,但是还不行,因为获取用户地理位置这样的LBS获取,需要申请权限,否则不允许的,程序会报错。
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" />
原文链接:http://www.apkbus.com/blog-894806-63307.html
點擊查看更多內容
1人點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦