反向地理编码-显示位置信息

GeocodeingAPI的使用:
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false
json 表示:返回的数据类型
接着是经纬值(北纬,西经)
表示是否来自某个设备的传感器。

下面的实例:用到异步操作,HttpURLConnection/HttpClient ,JSON的解析

package com.example.locationmanager;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

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.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private TextView posiotionTextView;
    private LocationManager locationManager;
    private String provider;
    public static final int SHOW_LOCATION = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        posiotionTextView =(TextView) findViewById(R.id.position_text_view);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providerList = locationManager.getProviders(true);
//       if(providerList.contains(LocationManager.GPS_PROVIDER)){
//            provider = LocationManager.GPS_PROVIDER;
//          System.out.println(provider);
//       }else
//
       if(providerList.contains(LocationManager.NETWORK_PROVIDER)){
            provider = LocationManager.NETWORK_PROVIDER;
            System.out.println(provider);

        }else {
            //当没有可用的位置提供器时,弹出Toast提示用户
            Toast.makeText(this , " No Location provider to use",Toast.LENGTH_SHORT).show();
            return;
        }
        if ( Build.VERSION.SDK_INT >= 23 &&
                ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return  ;
        }



        Location location = locationManager.getLastKnownLocation(provider);

        if (location!=null){

            showLocation(location);
        }
        locationManager.requestLocationUpdates(provider , 5000 , 1 ,locationListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationManager!=null){
            //关闭程序将监听器移除
            locationManager.removeUpdates(locationListener);
        }
    }

    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            //更新当前设备的位置信息
            showLocation(location);

        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    private  void showLocation(final Location location){//不加final无法在子线程中使用
        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(location.getLatitude()).append(",");
                    url.append(location.getLongitude());
                    url.append("&sensor=false");//sensor传感器
                    System.out.println(url);

                    HttpURLConnection httpURLConnection = null;
                    URL url1 = new URL(url.toString());
                    httpURLConnection = (HttpURLConnection) url1.openConnection();
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
                    httpURLConnection.setRequestProperty("Accept-Language","zh-CN");
                    if(httpURLConnection.getResponseCode()==200){
                        InputStream in = httpURLConnection.getInputStream();
                        BufferedReader reader = new BufferedReader((new InputStreamReader(in)));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }

                        JSONObject jsonObject = new JSONObject(response.toString());
                        JSONArray resultArray = jsonObject.getJSONArray("results");
                        System.out.println("解析数据成功");
                        if (resultArray.length()>0) {
                            JSONObject subObject = resultArray.getJSONObject(0);//返回JSON的formatted_address在第0个JSON对象里


                            String address = subObject.getString("formatted_address");
                            Message message = new Message();
                            message.what = SHOW_LOCATION ;
                            message.obj = address ;
                            handler.sendMessage(message);

                        }

                    }

//                    HttpClient httpClient = new DefaultHttpClient();
//                    HttpGet httpGet = new HttpGet(url.toString());
//                    httpGet.addHeader("Accept-Language","zh-CN");
//                    HttpResponse httpResponse = httpClient.execute(httpGet);
//                    System.out.println("---"+url.toString());
//
//                    if (httpResponse.getStatusLine().getStatusCode()==200){
//                        System.out.println("---"+"请求成功");
//                        HttpEntity entity = httpResponse.getEntity();
//                        String response = EntityUtils.toString(entity,"utf-8");
//
//                        JSONObject jsonObject = new JSONObject(response);
//                        JSONArray resultArray = jsonObject.getJSONArray("results");
//                        System.out.println("解析数据成功");
//
//                        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 ;
//                            handler.sendMessage(message);
//
//                        }
//                    }




                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

//        String currentPosition = "latitude is " +location.getLatitude()+"\n"+"longitude is"+ location.getLongitude();
//        System.out.println(currentPosition);
//        posiotionTextView.setText(currentPosition);
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case SHOW_LOCATION:
                    String currentPosition = (String)msg.obj;
                    System.out.println(currentPosition);
                    posiotionTextView.setText(currentPosition);
                    break;
                default:
                    break;

            }
        }
    };

}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.locationmanager">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
</manifest>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值