【问题标题】:Geocoding - Converting an address (in String form) into LatLng in GoogleMaps Java地理编码 - 在 GoogleMaps Java 中将地址(以字符串形式)转换为 LatLng
【发布时间】:2017-03-06 13:20:08
【问题描述】:

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

我在网上搜索这件事几乎没有结果,因为网上建议的代码很复杂,因为手头的问题是一个非常标准的问题。我认为 GoogleMaps API 中可能有一项功能可以让我这样做,但我找不到。对于我们这里的初学者,任何关于我如何做到这一点的指示?

【问题讨论】:

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


    【解决方案1】:

    您需要使用地理编码器。试试这个代码 sn-p:

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

    【讨论】:

    • 当我尝试你的代码时,我得到服务不可用。我重新启动了设备并且它工作了。谢谢+1!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    相关资源
    最近更新 更多