地理编码 - 在GoogleMaps Java中将地址(以字符串形式)转换为LatLng

时间:2017-03-06 13:20:08

标签: java android google-maps coordinates street-address

我是一名初学程序员,在大学学习了几门课程,因此对该领域没有完全的了解。我想我会尝试使用GoogleMaps API编写一个Android应用程序,并发现需要将用户输入的地址(字符串格式)转换为Google的补充LatLng类,或者更确切地说,提取纬度和经度坐标,以便输入LatLng构造函数(JAVA)。

我在网上搜索产生的结果很少甚至没有,因为在线提供的代码很复杂,因为手头的问题非常标准。我认为GoogleMaps API中可能有一个功能允许我这样做,但我找不到。对于我们这里的初学者,有关如何做到这一点的任何指示?

1 个答案:

答案 0 :(得分:5)

您需要使用Geocoder。试试这段代码:

public LatLng getLocationFromAddress(Context context, String inputtedAddress) {

    Geocoder coder = new Geocoder(context);
    List<Address> address;
    LatLng resLatLng = null;

    try {
        // May throw an IOException
        address = coder.getFromLocationName(inputtedAddress, 5);
        if (address == null) {
            return null;
        }

        if (address.size() == 0) {
            return null;
        }

        Address location = address.get(0);
        location.getLatitude();
        location.getLongitude();

        resLatLng = new LatLng(location.getLatitude(), location.getLongitude());

    } catch (IOException ex) {

        ex.printStackTrace();
        Toast.makeText(context, ex.getMessage(), Toast.LENGTH_LONG).show();
    }

    return resLatLng;
}