получить широту и долготу от названия города - PullRequest
4 голосов
/ 02 февраля 2011

В моем текущем приложении для Android я хотел бы получить геоординаты на основе введенного названия города, названия улицы или почтового индекса. Как мне это сделать?

С наилучшими пожеланиями

Ответы [ 3 ]

4 голосов
/ 14 марта 2012

получить географические координаты через сеть

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 голосов
/ 16 февраля 2012

искомый адрес -> Может быть (название города / адрес / почтовый индекс).

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 голосов
/ 02 февраля 2011

Используйте Геокодер класс.Это не сложно использовать, и тогда вы можете использовать getFromLocationName, который делает то, что вы хотите.Вы также можете использовать этот класс наоборот, например, ввести (lat, lon) и получить адрес, расположенный там.

Я предполагаю, что вы хотите сделать это с помощью кода Android, если вы хотите использоватьJavascript, тогда вы должны использовать API карты Google , как указано в другом ответе.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...