android - 如何从位置名称获取坐标

标签 android location coordinates

在我的应用程序中,用户键入一个位置,我必须获取该位置的纬度和经度。所以这里我没有 Location 对象,而是一个 String

我想到了使用此 String 创建 Location 对象的选项,但这是不可能的。

我知道可以使用 Google 的 places API,而且我知道如何使用它,但我更喜欢使用 SDK 中可用的任何方法。

有什么办法吗?

最佳答案

您可以使用 Geocoder .像这样:

Geocoder geocoder = new Geocoder(App.getContext(), Locale.US);
    List<Address> listOfAddress;
    try {
        listOfAddress = geocoder.getFromLocation(theLatitude, theLongitude, 1);
        if(listOfAddress != null && !listOfAddress.isEmpty()){
        Address address = listOfAddress.get(0);

        String country = address.getCountryCode();
        String adminArea= address.getAdminArea();
        String locality= address.getLocality();

    }
    } catch (IOException e) {
        e.printStackTrace();
    }

更新:从地址使用获取位置:

listOfAddress = geocoder.getFromLocationName("Address", 1);

并获取纬度、经度:

double latitude = address.getLatitude();
double longitude = address.getLongitude();

更新:当 Geocoder 返回 null 时使用此代码段获取位置:

private static final String URL = "http://maps.googleapis.com/maps/api/geocode/xml";

public static RemoteCommand getLocation(String theAddress){
    RemoteCommand result = new RemoteCommand();

    result.setType(Type.GET);
    result.setUrl(URL);
    result.addGetParam("address", theAddress);
    result.addGetParam("sensor", "false");
    result.addGetParam("language", "en");

    // See description about GeocoderXMLHandler
    result.setXmlHandler(new GeocoderXMLHandler());

    return result;
}

最良好的祝愿。

关于android - 如何从位置名称获取坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17276036/

相关文章:

java - 从 Okhttp 使用 One-Shot ResponseBody 会导致 Retrofit 出现问题

iphone - 多计算纬度/经度点之间的经纬度?

php - 如何防止包含的 PHP 脚本更改位置 URL?

go - Golang从坐标列表创建wkb.Polygon

javascript - 我如何比较两个 X、Y 坐标数据集以寻找相似之处?

Android:可以在 Activity 的 onCreate 之外放置 HTTP 请求吗?

java - 更改 OpenGL 来源

android - 使 webview 在有大量 fragment 的 tablayout 中仅加载一次

Php 位置 ("some other page")

vector - svg: 生成 'outline path'