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

4

在我的当前安卓应用中,我想通过输入城市名、街道名或邮编来获取地理坐标。我该如何实现?

最好的问候

3个回答

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

3

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

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

0
使用Geocoder类。它不难使用,然后你可以使用getFromLocationName,它会做你想要的事情。你也可以反过来使用这个类,也就是说,输入(纬度、经度),然后获取那里的地址。
我假设你想通过Android代码来完成,如果你想使用Javascript,那么你应该使用Google地图API,正如另一个答案所指出的。

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