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

时间:2013-12-02 09:59:33

标签: android location

我正在编写一个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);

5 个答案:

答案 0 :(得分:6)

 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;

}

答案 1 :(得分:2)

在这种情况下,您必须使用geocode api。这将返回一个json响应解析它,'locality'是您需要的城市。 Here是适当的文档。

http://maps.google.com/maps/api/geocode/json?address=19.701989,72.774733&sensor=false

答案 2 :(得分:1)

试试这段代码

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!");
}

答案 3 :(得分:1)

我不是本地化方面的专家,但也许你应该改变一下你的代码,以便更清楚你得到的结果。

 /*----------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);

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

答案 4 :(得分:0)

我花了一段时间才得到(很多Googleing和试错),但它确实有效! :)享受并感谢耶稣基督。

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:您位于英国伦敦