如何从地点名称获取坐标

5
在我的应用中,用户输入了一个地点,我需要获取该地点的纬度和经度。所以,这里没有“位置”对象,而是一个字符串。
我想到一种使用此字符串创建“位置”对象的选项,但这是不可能的。
我知道可以使用谷歌的places API实现这一点,我知道如何使用它,但我更喜欢使用SDK中提供的任何可用方法。
有什么办法可以做到这一点吗?
7个回答

4
您可以使用地理编码器。像这样:
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;
}

最好的祝愿。


第一个地址在列表中是否是位置名称的地址,这个说法有多准确? - Geek
你总是可以从地址中获取所有信息并进行检查。 - Yakiv Mospan
这个不起作用。geocoder.getFromLocationName(locationString, 1); 总是返回 null。我看到很多关于总是获取 null 的问题,最终他们摆脱了它并使用了 Google API。 - Geek
它并不总是在Android 4及以上版本中返回null。通常重新启动可以解决这个问题。但你说得对,我总是处理如果它是null,并且在需要时使用Geocoder API。回答已更新。如果正确,请标记答案为已接受。 - Yakiv Mospan
你尝试过使用 geocoder.getFromLocationName(locationString, 5); 并遍历响应吗?如果第一个为空,就继续迭代。 - Pulkit

3
String UrlCity = "http://maps.googleapis.com/maps/api/geocode/json?address=" + NameString + "&sensor=false";

        JsonObjectRequest stateReq = new JsonObjectRequest(Request.Method.GET, UrlState, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                JSONObject location;
                try {
                    // Get JSON Array called "results" and then get the 0th
                    // complete object as JSON
                    location = response.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location");
                    // Get the value of the attribute whose name is
                    // "formatted_string"
                    stateLocation = new LatLng(location.getDouble("lat"), location.getDouble("lng"));
                    // System.out.println(stateLocation.toString());
                } catch (JSONException e1) {
                    e1.printStackTrace();

                }
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("Error.Response", error.toString());
            }
        });
        // add it to the RequestQueue
        reqQueue.add(stateReq);

您可以通过使用Google Volley库或将其包装在AsyncTask或runnable中的简单http调用来从给定名称获取坐标。

希望这有所帮助!


2
除了Google geocode API之外,如yakiv.mospan所述,只有一种获取纬度和经度的可能性。但是“Geocoder”总是返回空值,许多人也是这种情况。我通过在stackoverflow.com上搜索此问题来了解这一点。
毕竟,由于没有其他选择,我决定使用{{link1:Google places API}}。

付款将在一些请求之后进行。 - Pulkit

0

你可以使用这段代码:

String add = address + "," + city + "," + country;

String addressUrl = "http://maps.googleapis.com/maps/api/geocode/json?address="
                + URLEncoder.encode(add.replaceAll(" ", "+"))
                + "&sensor=true";
try {
            HttpClient httpClient = new DefaultHttpClient();// Client

            HttpGet getRequest = new HttpGet();
            getRequest.setURI(new URI(addressUrl));

            // HttpPost postRequest = new HttpPost();
            // postRequest.setURI(new URI(url));

            HttpResponse response = httpClient.execute(getRequest);
            in = new BufferedReader(new InputStreamReader(response
                    .getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            String page = sb.toString();
            JSONObject jsonObject = new JSONObject(page);
            if (jsonObject.has("results")) {
                JSONArray jsonArray = (JSONArray) jsonObject.get("results");

                if (jsonArray.length() > 0) {
                    jsonObject = (JSONObject) jsonArray.get(0);
                    if (jsonObject.has("geometry")) {
                        jsonObject = (JSONObject) jsonObject
                                .get("geometry");

                        if (jsonObject.has("location")) {
                            JSONObject location = (JSONObject) jsonObject
                                    .get("location");

                            latitude = (Double) location.get("lat");
                            longitude = (Double) location.get("lng");
                            Log.e(TAG, "lat : " + latitude + " long : "
                                    + longitude);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

这是更多可以帮助您的链接:

谷歌地图 V2

谷歌地点 API 演示


0

我想获取坐标,而不是地址或位置名称。 - Geek

0

首先,你发的第一个链接是有关JavaScript的?我在哪里提到过JavaScript了吗?而且,我的问题中已经说过我知道这个API,至少完整地读一下问题再回答。 - Geek

-1
你可以使用这个。
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
geocoder.getFromLocation(LATITUDE, LONGITUDE, 3);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接