Android 使用纬度和经度获取特定地址

Android 使用纬度和经度获取特定地址,android,geolocation,Android,Geolocation,我需要知道是否有API,从那里我可以接收当前地点的地址。使用位置管理器,我已经接收到当前地点的纬度和经度,但我需要地址 我已经尝试了下面的api http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat + "," + lon + &sensor=true" 但是它没有显示确切的位置。有人能帮我吗。@谢谢。从一个对象,你可以调用这个方法 例如: private String getAddress(double lati

我需要知道是否有API,从那里我可以接收当前地点的地址。使用位置管理器,我已经接收到当前地点的纬度和经度,但我需要地址

我已经尝试了下面的api

http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat + "," + lon + &sensor=true"
但是它没有显示确切的位置。有人能帮我吗。@谢谢。

从一个对象,你可以调用这个方法

例如:

private String getAddress(double latitude, double longitude) {
        StringBuilder result = new StringBuilder();
        try {
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
            if (addresses.size() > 0) {
                Address address = addresses.get(0);
                result.append(address.getLocality()).append("\n");
                result.append(address.getCountryName());
            }
        } catch (IOException e) {
            Log.e("tag", e.getMessage());
        }

        return result.toString();
    }
私有字符串getAddress(双纬度、双经度){
StringBuilder结果=新建StringBuilder();
试一试{
Geocoder Geocoder=新的Geocoder(这个,Locale.getDefault());
列表

字符串longti=“0”;
字符串lati=“0”;
地点经理地点经理;
locationManager=(locationManager)getSystemService(Context.LOCATION\u服务);
locationManager.RequestLocationUpdate(locationManager.GPS\U提供程序,
1000,1,新的MyLocationListners();
最终位置=位置管理器
.getLastKnownLocation(LocationManager.GPS\U提供商);
//这是你的经度和纬度
lati=String.valueOf(location.getLatitude());
longti=String.valueOf(location.getLongitude());
//这里我们使用地理代码(经度和纬度)获得地址。
字符串ad=getAddress(location.getLatitude(),location.getLatitude());
私有字符串getAddress(双纬度、双经度){
字符串strAdd=“”;
Geocoder Geocoder=新的Geocoder(这个,Locale.getDefault());
试一试{
列表地址=地理编码器.getFromLocation(纬度,
经度,1);
如果(地址!=null){
返回的地址地址=地址。获取(0);
StringBuilder strReturnedAddress=新StringBuilder(“”);
对于(int i=0;i
//确保gps和互联网已打开 //有时,由于一些//谷歌服务问题,您在第一次运行代码时无法看到该位置,因此您必须重新启动手机
//希望这对您有所帮助

我创建了一个类,用于获取特定Lat的地址,Long。您可以使用此:

public class getReverseGeoCoding {
    private String Address1 = "", Address2 = "", City = "", State = "", Country = "", County = "", PIN = "";

    public void getAddress() {
        Address1 = "";
        Address2 = "";
        City = "";
        State = "";
        Country = "";
        County = "";
        PIN = "";

        try {

            JSONObject jsonObj = parser_Json.getJSONfromURL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + Global.curLatitude + ","
                    + Global.curLongitude + "&sensor=true");
            String Status = jsonObj.getString("status");
            if (Status.equalsIgnoreCase("OK")) {
                JSONArray Results = jsonObj.getJSONArray("results");
                JSONObject zero = Results.getJSONObject(0);
                JSONArray address_components = zero.getJSONArray("address_components");

                for (int i = 0; i < address_components.length(); i++) {
                    JSONObject zero2 = address_components.getJSONObject(i);
                    String long_name = zero2.getString("long_name");
                    JSONArray mtypes = zero2.getJSONArray("types");
                    String Type = mtypes.getString(0);

                    if (TextUtils.isEmpty(long_name) == false || !long_name.equals(null) || long_name.length() > 0 || long_name != "") {
                        if (Type.equalsIgnoreCase("street_number")) {
                            Address1 = long_name + " ";
                        } else if (Type.equalsIgnoreCase("route")) {
                            Address1 = Address1 + long_name;
                        } else if (Type.equalsIgnoreCase("sublocality")) {
                            Address2 = long_name;
                        } else if (Type.equalsIgnoreCase("locality")) {
                            // Address2 = Address2 + long_name + ", ";
                            City = long_name;
                        } else if (Type.equalsIgnoreCase("administrative_area_level_2")) {
                            County = long_name;
                        } else if (Type.equalsIgnoreCase("administrative_area_level_1")) {
                            State = long_name;
                        } else if (Type.equalsIgnoreCase("country")) {
                            Country = long_name;
                        } else if (Type.equalsIgnoreCase("postal_code")) {
                            PIN = long_name;
                        }
                    }

                    // JSONArray mtypes = zero2.getJSONArray("types");
                    // String Type = mtypes.getString(0);
                    // Log.e(Type,long_name);
                }
            }

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

    }

    public String getAddress1() {
        return Address1;

    }

    public String getAddress2() {
        return Address2;

    }

    public String getCity() {
        return City;

    }

    public String getState() {
        return State;

    }

    public String getCountry() {
        return Country;

    }

    public String getCounty() {
        return County;

    }

    public String getPIN() {
        return PIN;

    }

}

我试图修改由提供的类以使其更好

public class ReverseGeoCoding {
private String address1, address2, city, state, country, county, PIN;
private static final String LOG_TAG = ReverseGeoCoding.class.getSimpleName();

public ReverseGeoCoding(double latitude, double longitude) {
    init();
    retrieveData(latitude, longitude);
}

private void retrieveData(double latitude, double longitude) {
    try {
        String responseFromHttpUrl = getResponseFromHttpUrl(buildUrl(latitude, longitude));
        JSONObject jsonResponse = new JSONObject(responseFromHttpUrl);
        String status = jsonResponse.getString("status");
        if (status.equalsIgnoreCase("OK")) {
            JSONArray results = jsonResponse.getJSONArray("results");
            JSONObject zero = results.getJSONObject(0);
            JSONArray addressComponents = zero.getJSONArray("address_components");

            for (int i = 0; i < addressComponents.length(); i++) {
                JSONObject zero2 = addressComponents.getJSONObject(i);
                String longName = zero2.getString("long_name");
                JSONArray types = zero2.getJSONArray("types");
                String type = types.getString(0);


                if (!TextUtils.isEmpty(longName)) {
                    if (type.equalsIgnoreCase("street_number")) {
                        address1 = longName + " ";
                    } else if (type.equalsIgnoreCase("route")) {
                        address1 = address1 + longName;
                    } else if (type.equalsIgnoreCase("sublocality")) {
                        address2 = longName;
                    } else if (type.equalsIgnoreCase("locality")) {
                        // address2 = address2 + longName + ", ";
                        city = longName;
                    } else if (type.equalsIgnoreCase("administrative_area_level_2")) {
                        county = longName;
                    } else if (type.equalsIgnoreCase("administrative_area_level_1")) {
                        state = longName;
                    } else if (type.equalsIgnoreCase("country")) {
                        country = longName;
                    } else if (type.equalsIgnoreCase("postal_code")) {
                        PIN = longName;
                    }
                }
            }
        }

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

private void init() {
    address1 = "";
    address2 = "";
    city = "";
    state = "";
    country = "";
    county = "";
    PIN = "";
}

private URL buildUrl(double latitude, double longitude) {
    Uri uri = Uri.parse("http://maps.googleapis.com/maps/api/geocode/json").buildUpon()
            .appendQueryParameter("latlng", latitude + "," + longitude)
            .build();
    try {
        return new URL(uri.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        Log.e(LOG_TAG, "can't construct location object");
        return null;
    }
}

private String getResponseFromHttpUrl(URL url) throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        InputStream in = urlConnection.getInputStream();
        Scanner scanner = new Scanner(in);
        scanner.useDelimiter("\\A");
        if (scanner.hasNext()) {
            return scanner.next();
        } else {
            return null;
        }
    } finally {
        urlConnection.disconnect();
    }
}

public String getAddress1() { return address1; }

public String getAddress2() { return address2; }

public String getCity() { return city; }

public String getState() { return state; }

public String getCountry() { return country; }

public String getCounty() { return county; }

public String getPIN() { return PIN; }

}
公共类反向编码{
私有字符串地址1、地址2、城市、州、国家、县、PIN;
私有静态最终字符串LOG_TAG=ReverseGeoCoding.class.getSimpleName();
公共反向编码(双纬度、双经度){
init();
检索数据(纬度、经度);
}
私有无效检索数据(双纬度、双经度){
试一试{
字符串responseFromHttpUrl=getResponseFromHttpUrl(buildUrl(纬度、经度));
JSONObject jsonResponse=新的JSONObject(responseFromHttpUrl);
String status=jsonResponse.getString(“status”);
if(状态相等信号情况(“正常”)){
JSONArray results=jsonResponse.getJSONArray(“结果”);
JSONObject零=结果。getJSONObject(0);
JSONArray addressComponents=zero.getJSONArray(“address_components”);
对于(int i=0;ipublic class parser_Json {
    public static JSONObject getJSONfromURL(String url) {

        // initialize
        InputStream is = null;
        String result = "";
        JSONObject jObject = null;

        // http post
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObject = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jObject;
    }

}
public class ReverseGeoCoding {
private String address1, address2, city, state, country, county, PIN;
private static final String LOG_TAG = ReverseGeoCoding.class.getSimpleName();

public ReverseGeoCoding(double latitude, double longitude) {
    init();
    retrieveData(latitude, longitude);
}

private void retrieveData(double latitude, double longitude) {
    try {
        String responseFromHttpUrl = getResponseFromHttpUrl(buildUrl(latitude, longitude));
        JSONObject jsonResponse = new JSONObject(responseFromHttpUrl);
        String status = jsonResponse.getString("status");
        if (status.equalsIgnoreCase("OK")) {
            JSONArray results = jsonResponse.getJSONArray("results");
            JSONObject zero = results.getJSONObject(0);
            JSONArray addressComponents = zero.getJSONArray("address_components");

            for (int i = 0; i < addressComponents.length(); i++) {
                JSONObject zero2 = addressComponents.getJSONObject(i);
                String longName = zero2.getString("long_name");
                JSONArray types = zero2.getJSONArray("types");
                String type = types.getString(0);


                if (!TextUtils.isEmpty(longName)) {
                    if (type.equalsIgnoreCase("street_number")) {
                        address1 = longName + " ";
                    } else if (type.equalsIgnoreCase("route")) {
                        address1 = address1 + longName;
                    } else if (type.equalsIgnoreCase("sublocality")) {
                        address2 = longName;
                    } else if (type.equalsIgnoreCase("locality")) {
                        // address2 = address2 + longName + ", ";
                        city = longName;
                    } else if (type.equalsIgnoreCase("administrative_area_level_2")) {
                        county = longName;
                    } else if (type.equalsIgnoreCase("administrative_area_level_1")) {
                        state = longName;
                    } else if (type.equalsIgnoreCase("country")) {
                        country = longName;
                    } else if (type.equalsIgnoreCase("postal_code")) {
                        PIN = longName;
                    }
                }
            }
        }

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

private void init() {
    address1 = "";
    address2 = "";
    city = "";
    state = "";
    country = "";
    county = "";
    PIN = "";
}

private URL buildUrl(double latitude, double longitude) {
    Uri uri = Uri.parse("http://maps.googleapis.com/maps/api/geocode/json").buildUpon()
            .appendQueryParameter("latlng", latitude + "," + longitude)
            .build();
    try {
        return new URL(uri.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        Log.e(LOG_TAG, "can't construct location object");
        return null;
    }
}

private String getResponseFromHttpUrl(URL url) throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        InputStream in = urlConnection.getInputStream();
        Scanner scanner = new Scanner(in);
        scanner.useDelimiter("\\A");
        if (scanner.hasNext()) {
            return scanner.next();
        } else {
            return null;
        }
    } finally {
        urlConnection.disconnect();
    }
}

public String getAddress1() { return address1; }

public String getAddress2() { return address2; }

public String getCity() { return city; }

public String getState() { return state; }

public String getCountry() { return country; }

public String getCounty() { return county; }

public String getPIN() { return PIN; }

}
private class DownloadRawData extends AsyncTask<LatLng, Void, ArrayList<String>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
              progressDialog=new ProgressDialog(getActivity());
            progressDialog.setMessage("Loading........");
            progressDialog.setCancelable(false);
            progressDialog.show();
        }


        @Override
        protected ArrayList<String> doInBackground(LatLng... latLng) {
            ArrayList<String> strings=retrieveData(latLng[0].latitude,latLng[0].longitude);
            return strings;
        }

        @Override
        protected void onPostExecute(ArrayList<String> s) {
            super.onPostExecute(s);
            if(progressDialog!=null)
            progressDialog.dismiss();
            LocationInfoDialog locationinfoDialog=new LocationInfoDialog(getActivity(),s);
            locationinfoDialog.show();
            locationinfoDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            locationinfoDialog.setCancelable(false);
        }
    }

    private void init() {
        address1 = "";
        address2 = "";
        city = "";
        state = "";
        country = "";
        county = "";
        PIN = "";
    }
    private String createUrl(double latitude, double longitude) throws UnsupportedEncodingException {
        init();
        return "https://maps.googleapis.com/maps/api/geocode/json?" + "latlng=" + latitude + "," + longitude + "&key=" + getActivity().getResources().getString(R.string.map_apiid);
    }

    private URL buildUrl(double latitude, double longitude) {

        try {
            Log.w(TAG, "buildUrl: "+createUrl(latitude,longitude));
            return new URL(createUrl(latitude,longitude));
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.e(LOG_TAG, "can't construct location object");
            return null;
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String getResponseFromHttpUrl(URL url) throws IOException {
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        try {
            InputStream in = urlConnection.getInputStream();
            Scanner scanner = new Scanner(in);
            scanner.useDelimiter("\\A");
            if (scanner.hasNext()) {
                return scanner.next();
            } else {
                return null;
            }
        } finally {
            urlConnection.disconnect();
        }
    }

    public String getAddress1() { return address1; }

    public String getAddress2() { return address2; }

    public String getCity() { return city; }

    public String getState() { return state; }

    public String getCountry() { return country; }

    public String getCounty() { return county; }

    public String getPIN() { return PIN; }
    private ArrayList<String> retrieveData(double latitude, double longitude) {
        ArrayList<String> strings=new ArrayList<>();
        try {
            String responseFromHttpUrl = getResponseFromHttpUrl(buildUrl(latitude, longitude));
            JSONObject jsonResponse = new JSONObject(responseFromHttpUrl);
            String status = jsonResponse.getString("status");
            if (status.equalsIgnoreCase("OK")) {
                JSONArray results = jsonResponse.getJSONArray("results");
                JSONObject zero = results.getJSONObject(0);
                JSONArray addressComponents = zero.getJSONArray("address_components");
                String formatadd= zero.getString("formatted_address");

                for (int i = 0; i < addressComponents.length(); i++) {
                    JSONObject zero2 = addressComponents.getJSONObject(i);
                    String longName = zero2.getString("long_name");
                    JSONArray types = zero2.getJSONArray("types");
                    String type = types.getString(0);


                    if (!TextUtils.isEmpty(longName)) {
                        if (type.equalsIgnoreCase("street_number")) {
                            address1 = longName + " ";

                        } else if (type.equalsIgnoreCase("route")) {
                            address1 = address1 + longName;
                        } else if (type.equalsIgnoreCase("sublocality")) {
                            address2 = longName;
                        } else if (type.equalsIgnoreCase("locality")) {
                            // address2 = address2 + longName + ", ";
                            city = longName;
                        } else if (type.equalsIgnoreCase("administrative_area_level_2")) {
                            county = longName;
                        } else if (type.equalsIgnoreCase("administrative_area_level_1")) {
                            state = longName;
                        } else if (type.equalsIgnoreCase("country")) {
                            country = longName;
                        } else if (type.equalsIgnoreCase("postal_code")) {
                            PIN = longName;
                        }
                    }
                }
                strings.add(formatadd);
                strings.add(address1);
                strings.add(address2);
                strings.add(city);
                strings.add(county);
                strings.add(state);
                strings.add(country);

                strings.add(PIN);


            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  strings;
    }
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                markerOptions.position(latLng);

                // Setting the title for the marker.
                // This will be displayed on taping the marker
                markerOptions.title(latLng.latitude + " : " + latLng.longitude);
                googleMap.addMarker(markerOptions);
                new DownloadRawData().execute(latLng);
            }
        });