地理编码 - 在GoogleMaps Java中将地址(以字符串形式)转换为LatLng [英] Geocoding - Converting an address (in String form) into LatLng in GoogleMaps Java

查看:465
本文介绍了地理编码 - 在GoogleMaps Java中将地址(以字符串形式)转换为LatLng的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我在这方面的在线搜索几乎没有结果,因为在网上建议的代码是复杂的,因为手头的问题是相当标准的。我想到GoogleMaps API中可能有一个功能可以让我这样做,但我找不到它。对于我们这里的初学者来说,任何有关我如何做到这一点的指针? 你需要使用地理编码器。试试这段代码:

  public LatLng getLocationFromAddress(Context context,String inputsAddress){

Geocoder coder =新的Geocoder(上下文);
列表<地址>地址;
LatLng resLatLng = null;

try {
//可能抛出一个IOException异常
address = coder.getFromLocationName(inputsAddress,5);
if(address == null){
return null;
}

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

地址位置= 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();
}

返回resLatLng;
}


I'm a beginner programmer, took a few courses in university and therefore don't have a complete understanding of the field. I figured I'd give a shot at coding an android application with GoogleMaps API and found the need to convert a user inputted address (in String format) into Google's complementary LatLng class, or more precisely, extract latitude and longitude coordinates in order to input into the LatLng constructor (JAVA).

My search online in the matter yielded little to no results as the code suggested online is complex given the question at hand is a pretty standard one. I figured there is probably a feature in the GoogleMaps API that would allow me to do so, but I could not find one. For us beginners out here, any pointers on how I could do this ?

解决方案

You need to use Geocoder. Try this code snippet:

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

这篇关于地理编码 - 在GoogleMaps Java中将地址(以字符串形式)转换为LatLng的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆