从城市名称获取经度和纬度

时间:2011-02-02 10:09:34

标签: android google-maps

在我目前的Android应用程序中,我想根据输入的城市名称,街道名称或邮政编码获取坐标。我怎么能做到这一点?

最好的问候

3 个答案:

答案 0 :(得分:4)

通过网络获取地理坐标

private static JSONObject getLocationInfo(String address)
{

    StringBuilder stringBuilder = new StringBuilder();
    try {

    address = address.replaceAll(" ","%20");    

    HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    stringBuilder = new StringBuilder();


        response = client.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
        Log.i("getLocationInfo ClientProtocolException", e.toString());
    } catch (IOException e) {

        Log.i("getLocationInfo IOException", e.toString());
    }


    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        Log.i("getLocationInfo JSONException", e.toString());
    }

    return jsonObject;
}

private static boolean getLatLong(JSONObject jsonObject) 
{

    try {

       longitute = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
        Log.i("Log1", longitute1+"");
    latitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
            .getJSONObject("geometry").getJSONObject("location")
            .getDouble("lat");
        Log.i("lat1", latitude1+"");
    } catch (JSONException e) {

        longitute=0;
        latitude = 0;
        Log.i("getLatLong", e.toString());
        return false;

    }

    return true;
}

答案 1 :(得分:3)

searchingAddress - >可以是(城市名称/地址/邮政编码)。

public boolean getLatitudeAndLongitudeFromGoogleMapForAddress(String searchedAddress){

    Geocoder coder = new Geocoder(IPlant.iPlantActivity);
    List<Address> address;
    try 
    {
        address = coder.getFromLocationName(searchedAddress,5);
        if (address == null) {
            Log.d(TAG, "############Address not correct #########");
        }
        Address location = address.get(0);

        Log.d(TAG, "Address Latitude : "+ location.getLatitude();+ "Address Longitude : "+ location.getLongitude());
        return true;

    }
    catch(Exception e)
    {
        Log.d(TAG, "MY_ERROR : ############Address Not Found");
        return false;
    }
}

答案 2 :(得分:0)

使用Geocoder课程。它并不难使用,然后您可以使用getFromLocationName,它可以满足您的需求。您也可以反过来使用这个类,也就是说,输入(lat,lon)并获取位于那里的地址。

我假设您想通过Android代码执行此操作,如果您想使用Javascript,那么您应该使用Google map's API,如另一个答案所示。