Obtener Lat, Long desde la dirección

I want to get the latitude and longitude by entering the address, the following code i copied from aquí but in my case while i am passing full address its giving me error:

Caused by: java.lang.IllegalArgumentException: Illegal character in query at index 56: http://maps.google.com/maps/api/geocode/json?address=43 S BROADWAY, Pitman, New Jersey.

public static void getLatLongFromAddress(String youraddress) {
    String uri = "http://maps.google.com/maps/api/geocode/json?address=" +
                  youraddress + "&sensor=false";
    HttpGet httpGet = new HttpGet(uri);
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    try {
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());

        double lng = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
            .getJSONObject("geometry").getJSONObject("location")
            .getDouble("lng");

        dobule lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
            .getJSONObject("geometry").getJSONObject("location")
            .getDouble("lat");

        Log.d("latitude", lat);
        Log.d("longitude", lng);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

preguntado el 12 de junio de 14 a las 11:06

You can use below online tool to get lat and long from address workversatile.com/convert-address-to-lat-long -

6 Respuestas

You can't pass a space to a URL. Try to replace every space with %20 and you should be fine to go.

String replaced = yourString.replace(" ", "%20");

Información adicional W3Schools

Caracteres permitidos en una URL

How do I replace a character in a string in Java?

contestado el 23 de mayo de 17 a las 12:05

Utilizar :

youraddress = youraddress.replaceAll("\\s", "+");
String uri = "http://maps.google.com/maps/api/geocode/json?address=" +
              youraddress + "&sensor=false";

Replace all spaces to +, similar to the way google does. This is how we are using in our apps.

Respondido el 12 de junio de 14 a las 11:06

Should encode "youraddress" like

String encodedYourAddress = URLEncoder.encode(youraddress, "UTF-8");

and build the called URI as

String uri = "http://maps.google.com/maps/api/geocode/json?address="+encodedYourAddress+"&sensor=false";

Respondido el 12 de junio de 14 a las 11:06

You need to specify the current city or location reference from address any field name form address string and then you get the lat and lng like

`Geocoder geocoder = new Geocoder(this, Locale.getDefault()); List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);`

Por favor intente esto:

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

or further geocode need you :

Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(lat, lng, 1);
if (addresses.size() > 0) 
    System.out.println(addresses.get(0).getLocality());

Espero que esto te ayudará.

Respondido el 12 de junio de 14 a las 11:06

What have you changed? The point of SO is that other people with the same problem as the OP can reproduce and fix it. With a fixed code without explanation this is really hard to do. - UeliDeSchwert

you need to specified the current city or location reference from address any field name form address string and then you get the lat and lng like Geocoder geocoder = new Geocoder(this, Locale.getDefault()); List<Address> addresses = geocoder.getFromLocation(lat, lng, 1); - Ami Kamboj

You can use this function for that

public LatLng getLatLng(Context _context,String locn){
        Geocoder geocoder = new Geocoder(_context,Locale.getDefault());
        try{                
            List<Address> addresses = geocoder.getFromLocationName(locn, 5);
            if(addresses.size()>0)
            {                   
                GeoPoint p=new GeoPoint((int)(addresses.get(0).getLatitude()*1E6),(int)(addresses.get(0).getLongitude()*1E6));
                Double plat= (double) (p.getLatitudeE6())/1E6;
                Double plon =(double) (p.getLongitudeE6())/1E6;
                LatLng lonlat=new LatLng(plat,plon);
            }
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return lonlat;          
    }

Just pass the current context and the address as String that has to be converted to LatLng.The above function will return the LatLng value of the address.

And, You can get the corresponding Latitude and Longitude values as follows

double lat = lonlat.latitude;
double lng = lonlat.longitude;

Respondido el 13 de junio de 14 a las 19:06

I've same problem once. I figured it out using URLEncoder class.

I think you should encode your search term and put it in url like,

String query = URLEncoder.encode(address, "utf-8");
HttpGet httpGet = new HttpGet(
                "http://maps.google.com/maps/api/geocode/json?address="
                        + query + "&ka&sensor=false");

this is the best solution as per my understanding working for me.

Respondido 09 Jul 14, 06:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.