当前位置: 代码迷 >> Android >> “如何从 LatLong 获取实际文本值(地名)?”
  详细解决方案

“如何从 LatLong 获取实际文本值(地名)?”

热度:79   发布时间:2023-08-04 10:12:04.0

我正在 Android 中使用 GoogleMap。

到目前为止,我已经获得了当前位置并在其上显示了标记。

我从当前位置获得了 LatLong 值。

我可以使用以下代码获取城市名称:

            Geocoder gcd = new Geocoder(MainActivity.this, Locale.getDefault());
        List<Address> addresses = null;
        try {
            addresses = gcd.getFromLocation( mLocation.getLatitude(), mLocation.getLongitude(), 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (addresses.size() > 0)
            System.out.println(addresses.get(0).getLocality());
            Toast.makeText(MainActivity.this,""+addresses.get(0).getLocality(),Toast.LENGTH_LONG).show();
    }

但是,无法获得实际区域名称,即Bodakdev char rasta , Ahmedab??ad。

现在,我的问题是:如何从 LatLong 获取实际文本值(地名)?

您可以通过 Google 地图中的Geocoder对象获取此信息。 方法getFromLocation(double, double, int)完成这项工作。

Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());

addresses = geocoder.getFromLocation(latitude, longitude, 1); //  1 represent max location result to returned, by documents it recommended 1 to 5

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(); 

用这个,

Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(MyLat, MyLong, 1);
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
String address = addresses.get(0).getAddressLine(0);

您还可以从地方的邮政编码或邮政编码中获取城市名称

private fun getLatLngByZipcode(zipcode: String): String {
    var place = context.getString(R.string.location)
    val geocoder = Geocoder(context, Locale.getDefault())
    try {
        val addresses = geocoder.getFromLocationName(zipcode, 5)
        addresses?.forEach{
            it?.locality?.apply {
                place=this
            }
        }
    }
    catch (e: IOException) {
        LogUtils.error(TAG,e.message)
    }
    return place
}