如何从Google Maps的经纬度坐标中获取城市名称?

138

如果我只有一个城镇或地区的纬度和经度坐标,如何在谷歌地图上获取该城市的名称?

我尝试使用纬度和经度,可以获取国家信息,但不知道如何获取城市名称。

15个回答

249

通过Geocoder对象,您可以调用getFromLocation(double, double, int)方法。它将返回一个Address对象列表,其中包含一个getLocality()方法。

Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(lat, lng, 1);
if (addresses.size() > 0) {
    System.out.println(addresses.get(0).getLocality());
}
else {
   // do your stuff
}

2
我遇到了一个错误,提示“等待服务器响应超时”。我已经添加了互联网权限。还需要其他什么吗? - Bhaumik Belani
5
有时候 getLocality() 方法会返回 null,导致城市名仍保持在 mAdminArea 中。 - Leo DroidCoder
2
对于美国(和其他一些国家)的地址,请使用getAdminArea()返回州。 - Dustfinger
1
请勿使用地理编码器。它在许多设备上会抛出异常,并需要重新启动才能正常工作。 - Prasad Pawar
1
getLocality() 有时会返回 nullgetAdminArea() 返回加拿大的省或州,而 getSubAdminAread() 返回城市,但是有些奇怪,例如“多伦多分部”。 - ericn
显示剩余3条评论

28

我正在使用这段代码。你也可以使用它来获取有关纬度和经度的城市和其他详细信息:

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&key=YOUR_API_KEY");
            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;
        
    }
    
}

如何获取Google地图API密钥的详细信息,请参阅此处

JSON解析器类

public 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;
    }

}

您可以从此问题中获取更多信息:使用纬度和经度获取特定地址


@ErumHannan 你可以在你的服务中这样做 ** new getReverseGeoCoding().getCity(); ** 这将返回一个全局类中的当前城市或经纬度。 - Vipul Purohit
我使用了你的代码,但是它返回了一个错误,错误信息为{"error_message":"您必须使用API密钥对每个请求进行身份验证才能访问Google Maps平台API。有关更多信息,请参阅http://g.co/dev/maps-no-account","results":[],"status":"REQUEST_DENIED"}。我该如何解决这个问题? - Mohsen Hatami

12

试试这个

  List<Address> list = geoCoder.getFromLocation(location
            .getLatitude(), location.getLongitude(), 1);
    if (list != null & list.size() > 0) {
        Address address = list.get(0);
        result = address.getLocality();
        return result;

9

只需使用此方法并传递您的经纬度。

public static void getAddress(Context context, double LATITUDE, double LONGITUDE) {

//Set Address
try {
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
    List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
    if (addresses != null && addresses.size() > 0) {



        String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
        String city = addresses.get(0).getLocality();
        String state = addresses.get(0).getAdminArea();
        String country = addresses.get(0).getCountryName();
        String postalCode = addresses.get(0).getPostalCode();
        String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

        Log.d(TAG, "getAddress:  address" + address);
        Log.d(TAG, "getAddress:  city" + city);
        Log.d(TAG, "getAddress:  state" + state);
        Log.d(TAG, "getAddress:  postalCode" + postalCode);
        Log.d(TAG, "getAddress:  knownName" + knownName);

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

这个有什么新的东西,不在现有的答案中吗? - OrangeDog
@OrangeDog 一个使用Try Catch异常处理的简化方法,让其他人可以轻松理解。 - Hamza Khan

8

请尝试以下代码,希望对您有用:

CityAsyncTask cst = new CityAsyncTask(HomeScreenUserLocation.this,
                latitude, longitude);
        cst.execute();

        String lo = null;
        try {
            lo = cst.get().toString();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

and AsyncTask

public class CityAsyncTask extends AsyncTask<String, String, String> {
    Activity act;
    double latitude;
    double longitude;

    public CityAsyncTask(Activity act, double latitude, double longitude) {
        // TODO Auto-generated constructor stub
        this.act = act;
        this.latitude = latitude;
        this.longitude = longitude;
    }

    @Override
    protected String doInBackground(String... params) {
        String result = "";
        Geocoder geocoder = new Geocoder(act, Locale.getDefault());
        try {
            List<Address> addresses = geocoder.getFromLocation(latitude,
                    longitude, 1);
            Log.e("Addresses", "-->" + addresses);
            result = addresses.get(0).toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

    }
}

3

试试这个

var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);

geocoder.geocode(
{'latLng': latlng}, 
function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                var add= results[0].formatted_address ;
                var  value=add.split(",");

                count=value.length;
                country=value[count-1];
                state=value[count-2];
                city=value[count-3];
                alert("city name is: " + city);
            }
            else  {
                alert("address not found");
            }
    }
     else {
        alert("Geocoder failed due to: " + status);
    }
}

);


3
 private class MatchingNearByLocationTask extends
        AsyncTask<Void, Void, Void> 
 {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog

        progressDialog = new ProgressDialog(mContext);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(true);
        progressDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {

        jsonStr = getLocationInfo(Latitude, Longitude).toString();
        if (jsonStr != null) {
            Log.i("location--??", jsonStr);

            JSONObject jsonObj;
            try {
                jsonObj = new JSONObject(jsonStr);

                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 (Type.equalsIgnoreCase("administrative_area_level_2")) {
                            // Address2 = Address2 + long_name + ", ";
                            String City = long_name;
                            Log.d(" CityName --->", City + "");
                        }
                    }
                }

            }

            catch (JSONException e) {

                e.printStackTrace();
            }

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

    }

    @Override
    protected void onCancelled() {

        super.onCancelled();
        progressDialog.dismiss();

    }

}




private JSONObject getLocationInfo(double lat, double lng) {

    HttpGet httpGet = new HttpGet(
            "http://maps.googleapis.com/maps/api/geocode/json?latlng="
                    + lat + "," + lng + "&sensor=false");
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    try {
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jsonObject;
}

1
请参考以下代码。
 Geocoder geocoder = new Geocoder(this, Locale.getDefault());
     List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
     String cityName = addresses.get(0).getAddressLine(0);
     String stateName = addresses.get(0).getAddressLine(1);
     String countryName = addresses.get(0).getAddressLine(2);

1

1
我找到了解决这个问题的新方法。在这里,我使用了Google的HTTP服务来获取基于经纬度的位置的全部信息。您只需要在URL中传递纬度和经度以及您的API密钥(例如:latlng=21.1497409, 79.08747970000002 & key=YOUR API KEY)。以下是ExampleService类中的我的获取服务。
 getService(url) {

    return this.http.get(url).map((data: any) => data.json())

}

这段文字的意思是:你可以将此代码放在任何位置,并从需要位置数据的组件中调用下面的服务。
this._exampleService.getService("https://maps.googleapis.com/maps/api/geocode/json?latlng=21.1497409, 79.08747970000002&key=YOUR API KEY").subscribe(getplaceData => {
            var placeDataDest: any;
            placeDataDest = getplaceData;
            console.log("i got place id yeee " + placeDataDest['results'][0]['place_id']);
            console.log("i got place details yeee " + placeDataDest['results']);
        });

同样地,找到城市名称....希望您会发现这很有用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接