使用手机上的GPS查找城市名称

时间:2014-01-23 14:16:23

标签: java android geolocation gps location

我知道如何使用此方法根据坐标获取城市名称:

Geocoder gcd = new Geocoder(this, Locale.UK);
            List<Address> addresses = gcd.getFromLocation(52.95477000, -1.15808600,1);
            if (addresses.size() > 0) 
            {
                StringBuilder cityName = new StringBuilder();                
                cityName.append(addresses.get(0).getLocality());
                txtLat2.setText(cityName.toString());
                //Check if the user is in allowed cities
                if(cityName.toString().contains("Nottingham") )
                {
                 //If correct allow user to continue
                 enableDisableButtons(true);                
                }
                else
                {
                 //If not print a message
                 alert();
                 locationManager.removeUpdates(this);                
                }
            }    

但我希望它只适用于特定城市。然而,我注意到像英国诺丁汉这样的城市有许多不同的城市,其名称相同,如美国的诺丁汉。我的问题是,有没有办法确保用户在允许的城市(在我的情况下,诺丁汉英国而不是诺丁汉美国)?

2 个答案:

答案 0 :(得分:0)

Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(52.95477000, -1.15808600,1);

String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);

答案 1 :(得分:0)

您可以通过从返回的地址对象获取国家/地区代码(ISO 3166-1),并使用国家/地区代码/城市列表作为组合过滤器来执行此操作。有关地址的所有可用方法,请参阅开发人员页面:http://developer.android.com/reference/android/location/Address.html

Geocoder gcd = new Geocoder(this, Locale.UK);
    List<Address> addresses = gcd.getFromLocation(52.95477000, -1.15808600,1);
    if (addresses.size() > 0) 
    {
        String country = addresses.get(0).getCountryCode();
        String city    = addresses.get(0).getLocality();

        //Check if the user is in allowed cities
        switch ( country )
        {
        case "UK":                if(cityName.contains("Nottingham") )
                    {
                     //If correct allow user to continue
                     enableDisableButtons(true);                
                    }
                    else
                    {
                     //If not print a message
                     alert();
                     locationManager.removeUpdates(this);                
                    }

            break;
        }
    }
相关问题