0

I want to get the latitude and longitude by entering the address, the following code i copied from here 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();
    }
}
Spook
  • 25,318
  • 18
  • 90
  • 167
Rajesh Panchal
  • 1,140
  • 3
  • 20
  • 39
  • You can use below online tool to get lat and long from address https://www.workversatile.com/convert-address-to-lat-long – Arshad Shaikh Aug 23 '22 at 18:19

6 Answers6

2

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");

Further information: W3Schools

Characters allowed in a URL

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

Community
  • 1
  • 1
UeliDeSchwert
  • 1,146
  • 10
  • 23
2

Use :

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.

ngrashia
  • 9,869
  • 5
  • 43
  • 58
0

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);`

Please try this:

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());

Hope this will help you.

Ami Kamboj
  • 105
  • 1
  • 10
  • 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 Jun 12 '14 at 10:12
  • http://developer.android.com/reference/android/location/Geocoder.htmlplease specified here – Ami Kamboj Jun 12 '14 at 10:14
  • 1
    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
    addresses = geocoder.getFromLocation(lat, lng, 1);
    – Ami Kamboj Jun 12 '14 at 10:19
0

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";
iflorit
  • 740
  • 5
  • 10
0

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;
Lal
  • 14,726
  • 4
  • 45
  • 70
0

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.

Jaydipsinh Zala
  • 16,558
  • 7
  • 41
  • 45