获取当前位置城市名称,android

sycxhyv7  于 2022-12-31  发布在  Android
关注(0)|答案(5)|浏览(188)

我正在写一个Android应用程序,以获得当前位置的城市名称,我得到的纬度和经度的权利,但我不能得到城市名称.这里是我的代码:

// To get City-Name from coordinates
String cityName = null;               
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());              
List<Address> addresses = null;  
try {  
    addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);  
    if (addresses.size() > 0)  
    System.out.println(addresses.get(0).getLocality());  
    cityName = addresses.get(0).getLocality();  
} catch (IOException e) {             
    e.printStackTrace();  
} 

String s = longitude + "\n" + latitude + "\n\nMy Currrent City is: " + cityName;
editLocation.setText(s);
goucqfw6

goucqfw61#

public String getLocationName(double lattitude, double longitude) {

    String cityName = "Not Found";
    Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
    try {

        List<Address> addresses = gcd.getFromLocation(lattitude, longitude,
                10);

        for (Address adrs : addresses) {
            if (adrs != null) {

                String city = adrs.getLocality();
                if (city != null && !city.equals("")) {
                    cityName = city;
                    System.out.println("city ::  " + cityName);
                } else {

                }
                // // you should also try with addresses.get(0).toSring();

            }

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return cityName;

}
sauutmhj

sauutmhj2#

在这种情况下你必须使用geocode API,这会返回一个json响应,解析它,“locality”是你需要的城市,Here是正确的文档。
http://maps.google.com/maps/api/geocode/json?address=19.701989,72.774733&sensor=false

r7xajy2e

r7xajy2e3#

试试这个代码

Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);

 try {
 List<Address> addresses = geocoder.getFromLocation(yourLATITUDE, yourLONGITUDE, 1);

 if(addresses != null) {
 Address returnedAddress = addresses.get(0);
 StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
 for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
 strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
  }
 yourtextbox.setText(strReturnedAddress.toString());
 }
 else{
 myAddress.setText("No Address returned!");
 }
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
myAddress.setText("Canont get Address!");
}
f4t66c6m

f4t66c6m4#

我不是本地化方面的Maven,但也许你应该稍微修改一下代码,以更清楚地了解你得到的结果。

/*----------to get City-Name from coordinates ------------- */
            String cityName = "Not Found";                 
            Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());        
            try 
            {  
                List<Address> addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);  
                if (addresses.size() > 0) 
                { 
                    cityName = addresses.get(0).getLocality();  
                    // you should also try with addresses.get(0).toSring();
                    System.out.println(cityName); 
                }
            } catch (IOException e) 
            {                 
             e.printStackTrace();  
            } 

            String s = longitude+"\n"+latitude +"\n\nMy Currrent City is: "+cityName;
            editLocation.setText(s);

如果你得到了“未找到”,你可以更深入。

lf3rwulv

lf3rwulv5#

这花了我一段时间才得到(大量的谷歌和试错),但它的工作!:)享受和感谢耶稣基督。

protected class RetrieveGoogleMapsCityName extends AsyncTask<URL, Integer, Void> {
    protected AppCompatActivity a;
    protected AlertDialog dialog;

    private RetrieveGoogleMapsCityName(AppCompatActivity a) {
        this.a = a;
    }

    @Override
    protected void onPreExecute() {
        this.dialog = new AlertDialog.Builder(this.a).create();
        this.dialog.setCancelable(false);
        this.dialog.setMessage("*****");
        this.dialog.setTitle("*****");
        this.dialog.show();
    }

    @Override
    protected Void doInBackground(URL... urls) {
        try {
            final HttpURLConnection conn;
            conn = (HttpURLConnection) urls[0].openConnection();
            conn.setUseCaches(false);
            conn.setAllowUserInteraction(false);
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),
                    "UTF-8"), 8);

            StringBuilder sb = new StringBuilder();

            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            if (!sb.toString().isEmpty()) {
                JSONObject obj = new JSONObject(sb.toString());
                JSONArray results = obj.getJSONArray("results");
                JSONArray address_components = results.getJSONObject(0).getJSONArray("address_components");

                for (int i = 0; i < address_components.length(); i++) {
                    //Log.v("JSONArray", address_components.getJSONObject(i).getString("long_name"));
                    //Log.v("JSONArrayTypes", address_components.getJSONObject(i).getJSONArray("types").getString(0));

                    if (address_components.getJSONObject(i).getJSONArray("types").getString(0).contentEquals("locality")) {
                        Log.v("JSONArray:i", i + " " + address_components.getJSONObject(i).getString("long_name"));
                        cityName = address_components.getJSONObject(i).getString("long_name");
                    }
                    if (address_components.getJSONObject(i).getJSONArray("types").getString(0).contentEquals("administrative_area_level_1")) {
                        stateLetters = address_components.getJSONObject(i).getString("short_name");
                    }
                }
                /*cityName =
                        obj.getJSONArray("results").getJSONObject(0)
                                .getJSONArray("address_components").getJSONObject(1).getString("long_name");
                stateLetters = obj.getJSONArray("results").getJSONObject(0)
                        .getJSONArray("address_components").getJSONObject(4).getString("short_name");*/
            }
            if (conn != null) {
                conn.disconnect();
            }
            if (reader != null) {
                reader.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void v) {
        this.dialog.dismiss();
        hasLocation = true;
        Log.v("onPostExecute", "You are located in " + cityName + ", " + stateLetters);
    }
}

结果:您位于北卡罗来纳州夏洛特市****结果2:您位于英国伦敦

相关问题