get latitude and longitude with geocoder and android Google Maps API v2
Asked Answered
A

5

23

I'm using the Google Maps API v2 for android and works properly. However, I am trying to use geocoder to get the longitude and latitude of an address, but without success.

It has changed the way to do it from the v2?

I am using the conventional code

Geocoder gc = new Geocoder(context);
//...
  List<Address> list = gc.getFromLocationName("1600 Amphitheatre Parkway, Mountain View, CA", 1);

  Address address = list.get(0);

  double lat = address.getLatitude();
  double lng = address.getLongitude();
//...

Always returns a forced shutdown, and Log solves nothing. When using a block of try / catch, opens the map but always with the same location Use the Internet permission, I have included in the project also COARSE_LOCATION I have used various codes located here and on other sites, but without success.

Thank you in advance.

Antidisestablishmentarianism answered 29/3, 2013 at 21:13 Comment(3)
do you have android.permission.INTERNET permission set?Ommiad
You say log solves nothing, maybe you should include it anyway (I bet it actually does have some clues on what is wrong).Dime
I have the internet permission, logs, thanks:03-29 22:25:10.922: E/AndroidRuntime(4359): java.lang.RuntimeException: Unable to start activity ComponentInfo{blue.ninja.master/blue.ninja.master.Hola}: java.lang.NullPointerException 03-29 22:25:10.922: E/AndroidRuntime(4359): at android.app.ActivityThread.access$600(ActivityThread.java:130) 03-29 22:25:10.922: E/AndroidRuntime(4359): at android.app.ActivityThread 03-29 22:25:10.922: E/AndroidRuntime(4359): Caused by: java.lang.NullPointerException 03-29 22:25:10.922: E/AndroidRuntime(4359): at blue.ninja.master.Hola.onCreate(Hola.java:50)Antidisestablishmentarianism
D
54

Try this solution using this example url:

http://maps.google.com/maps/api/geocode/json?address=mumbai&sensor=false

which returns data in json format with lat/lng of address.

private class DataLongOperationAsynchTask extends AsyncTask<String, Void, String[]> {
   ProgressDialog dialog = new ProgressDialog(MainActivity.this);
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog.setMessage("Please wait...");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    @Override
    protected String[] doInBackground(String... params) {
        String response;
        try {
            response = getLatLongByURL("http://maps.google.com/maps/api/geocode/json?address=mumbai&sensor=false");
            Log.d("response",""+response);
            return new String[]{response};
        } catch (Exception e) {
            return new String[]{"error"};
        }
    }

    @Override
    protected void onPostExecute(String... result) {
        try {
            JSONObject jsonObject = new JSONObject(result[0]);

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

            double 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();
        }
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}


public String getLatLongByURL(String requestURL) {
    URL url;
    String response = "";
    try {
        url = new URL(requestURL);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        conn.setDoOutput(true);
        int responseCode = conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = br.readLine()) != null) {
                response += line;
            }
        } else {
            response = "";
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}

Hope this will helps you.

Dup answered 1/4, 2013 at 16:43 Comment(8)
@AmolSawant96Kuli is this solution working fine? I ask you because I see that Geocoder doesn't work well...Bookrack
Is it client-side geocoding or server-side? Unfortunately I am unable to find the difference in code because there is no proper example out there.Astylar
Can you please update the code? It seems HttpClient is deprecated and isn't available on Android 6 anymore.Sofar
@android developer, Thanks for updating. I updated my code as per new new Android version 6.Dup
@AmolSawant96Kuli Thank you. Say, is it really ok to use Google's website this way? No need to register for them or something?Sofar
I think you should also use Uri.Builder instead of a constant string, so that it should automatically replace the characters as needed.Sofar
Here. this is better for the URL creation: String queryUrl = new Uri.Builder().scheme("http").authority("maps.google.com").appendPath("maps").appendPath("api").appendPath("geocode") .appendPath("json").appendQueryParameter("address", query).appendQueryParameter("sensor", "false").build().toString();Sofar
Does this code still work for you? I'm getting a network timeout and 0 results. The alternatives to this solution are pretty ugly, so I'm really hoping this can still work for me.Auk
D
8

Try this out.

private void getLatLongFromAddress(String address)
{
    double lat= 0.0, lng= 0.0;

    Geocoder geoCoder = new Geocoder(this, Locale.getDefault());    
    try 
    {
        List<Address> addresses = geoCoder.getFromLocationName(address , 1);
        if (addresses.size() > 0) 
        {            
            GeoPoint p = new GeoPoint(
                    (int) (addresses.get(0).getLatitude() * 1E6), 
                    (int) (addresses.get(0).getLongitude() * 1E6));

            lat=p.getLatitudeE6()/1E6;
            lng=p.getLongitudeE6()/1E6;

            Log.d("Latitude", ""+lat);
            Log.d("Longitude", ""+lng);
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
Dup answered 30/3, 2013 at 4:40 Comment(3)
seems that the problem is a bug of android: code.google.com/p/android/issues/detail?id=8816 ...I do not know how to fix it :(((Antidisestablishmentarianism
@MiguelC : Could you find LatLng using address? Am facing same problem.Boulevard
I find that for me the results are always in the wrong country (even if I include the country in the address).Vulgarize
L
2

since the HttpClient has been depreciated, you may try the following code with Asynctask (also note that we need to encode the address into URL) :

public class GeoCoding extends AsyncTask<Void, Void, Void> {
    private String address;
    private static final String TAG = GeoCoding.class.getSimpleName();
    JSONObject jsonObj;
    String URL;
    private String Address1 = "", Address2 = "", City = "", State = "", Country = "", County = "", PIN = "", Area="";
    private  double latitude, longitude;
    HttpURLConnection connection;
    BufferedReader br;
    StringBuilder sb ;

    public GeoCoding(String address){
        this.address = address;
    }

    public String getArea(){
        return Area;
    }

    public void getAddress() {
        Address1 = "";
        Address2 = "";
        City = "";
        State = "";
        Country = "";
        County = "";
        PIN = "";
        Area ="";

        try {

            String Status = jsonObj.getString("status");
            if (Status.equalsIgnoreCase("OK")) {
                JSONArray Results = jsonObj.getJSONArray("results");
                JSONObject zero = Results.getJSONObject(0);
                JSONArray address_components = zero.getJSONArray("address_components");

                for (int i = 0; i < address_components.length(); i++) {
                    JSONObject zero2 = address_components.getJSONObject(i);
                    String long_name = zero2.getString("long_name");
                    JSONArray mtypes = zero2.getJSONArray("types");
                    String Type = mtypes.getString(0);

                    if (! TextUtils.isEmpty(long_name) || !long_name.equals(null) || long_name.length() > 0 || !long_name.equals("")) {
                        if (Type.equalsIgnoreCase("street_number")) {
                            Address1 = long_name + " ";
                        } else if (Type.equalsIgnoreCase("route")) {
                            Address1 = Address1 + long_name;
                        } else if (Type.equalsIgnoreCase("sublocality")) {
                            Address2 = long_name;
                        } else if (Type.equalsIgnoreCase("locality")) {
                            City = long_name;
                        } else if (Type.equalsIgnoreCase("administrative_area_level_2")) {
                            County = long_name;
                        } else if (Type.equalsIgnoreCase("administrative_area_level_1")) {
                            State = long_name;
                        } else if (Type.equalsIgnoreCase("country")) {
                            Country = long_name;
                        } else if (Type.equalsIgnoreCase("postal_code")) {
                            PIN = long_name;
                        }else if( Type.equalsIgnoreCase("neighborhood")){
                            Area = long_name;
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public void getGeoPoint(){
        try{
             longitude = ((JSONArray)jsonObj.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lng");
            latitude = ((JSONArray)jsonObj.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lat");

        }catch (Exception e){
            e.printStackTrace();
        }

    }


    @Override
    protected Void doInBackground(Void... params)  {
        try {
            StringBuilder urlStringBuilder = new StringBuilder("http://maps.google.com/maps/api/geocode/json");
            urlStringBuilder.append("?address=" + URLEncoder.encode(address, "utf8"));
            urlStringBuilder.append("&sensor=false");
            URL = urlStringBuilder.toString();
            Log.d(TAG, "URL: " + URL);

            URL url = new URL(URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.connect();
            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb = sb.append(line + "\n");
            }
        }catch (Exception e){e.printStackTrace(); }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        try {
            Log.d(TAG, "response code: " + connection.getResponseCode());
            jsonObj = new JSONObject(sb.toString());
            Log.d(TAG, "JSON obj: " + jsonObj);
            getAddress();
            Log.d(TAG, "area is: " + getArea());
            getGeoPoint();
            Log.d("latitude", "" + latitude);
            Log.d("longitude", "" + longitude);


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onPostExecute(aVoid);
    }
}
Legendary answered 30/6, 2015 at 9:0 Comment(0)
S
0

A simple rectification that worked for me is to just enable the internet connection on the device. Suggestion by Pxaml.

Suburban answered 1/3, 2018 at 11:3 Comment(0)
B
-11

you can get latitude and longitude of current location by this simple code

GPS_Location mGPS = new GPS_Location(MyApplication.getAppContext());

    if (mGPS.canGetLocation) {

        mLat = mGPS.getLatitude();
        mLong = mGPS.getLongitude();

    } else {
        System.out.println("cannot find");
    }

You must add gps and other permissions to your app

Benzoyl answered 8/6, 2013 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.