3

I am using google map v2 android and map is too displayed in my app. I just want to get latitude and longitude from a given address.

Example: In text field if I type "Indore", then I get the latitude and longitude of this city.

4 Answers4

11

You can use this method

 public void getLatLongFromPlace(String place) {
            try {
                Geocoder selected_place_geocoder = new Geocoder(context);
                List<Address> address;

                address = selected_place_geocoder.getFromLocationName(place, 5);

                if (address == null) {
                    d.dismiss();
                } else {
                    Address location = address.get(0);
                               Latitude lat= location.getLatitude();
                Longitude lng = location.getLongitude();

                }

            } catch (Exception e) {
                e.printStackTrace();
fetchLatLongFromService fetch_latlng_from_service_abc = new fetchLatLongFromService(
                        place.replaceAll("\\s+", ""));
                fetch_latlng_from_service_abc.execute();

            }

        }


//Sometimes happens that device gives location = null

    public class fetchLatLongFromService extends
                AsyncTask<Void, Void, StringBuilder> {
            String place;


            public fetchLatLongFromService(String place) {
                super();
                this.place = place;

            }

            @Override
            protected void onCancelled() {
                // TODO Auto-generated method stub
                super.onCancelled();
                this.cancel(true);
            }

            @Override
            protected StringBuilder doInBackground(Void... params) {
                // TODO Auto-generated method stub
                try {
                    HttpURLConnection conn = null;
                    StringBuilder jsonResults = new StringBuilder();
                    String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?address="
                            + this.place + "&sensor=false";

                    URL url = new URL(googleMapUrl);
                    conn = (HttpURLConnection) url.openConnection();
                    InputStreamReader in = new InputStreamReader(
                            conn.getInputStream());
                    int read;
                    char[] buff = new char[1024];
                    while ((read = in.read(buff)) != -1) {
                        jsonResults.append(buff, 0, read);
                    }
                    String a = "";
                    return jsonResults;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;

            }

        @Override
        protected void onPostExecute(StringBuilder result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            try {
                JSONObject jsonObj = new JSONObject(result.toString());
                JSONArray resultJsonArray = jsonObj.getJSONArray("results");

                // Extract the Place descriptions from the results
                // resultList = new ArrayList<String>(resultJsonArray.length());

                JSONObject before_geometry_jsonObj = resultJsonArray
                        .getJSONObject(0);

                JSONObject geometry_jsonObj = before_geometry_jsonObj
                        .getJSONObject("geometry");

                JSONObject location_jsonObj = geometry_jsonObj
                        .getJSONObject("location");

                String lat_helper = location_jsonObj.getString("lat");
                double lat = Double.valueOf(lat_helper);


                String lng_helper = location_jsonObj.getString("lng");
                double lng = Double.valueOf(lng_helper);


                LatLng point = new LatLng(lat, lng);


            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
        }
    }

The usual method to find the location is the one which i had mentioned earlier but sometime the network provider or GPS provider is not able to fetch location thus gives null value,it happened with me also but when the location is null and an exception is thrown,use the google web service to fetch the lat and long.First try to fetch from the above method and if it fails which happens sometimes go with the second method to fetch it from a web service.

codeRider
  • 685
  • 1
  • 5
  • 14
4

hi please use below google api for this purpose!!

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

you can use given below function in yours program to fetch latitude and longitude

public static void getLatLongFromGivenAddress(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());

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

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

}

to check this api please visit below link

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

you will get following json which you need to parse

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Indore",
               "short_name" : "Indore",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Indore",
               "short_name" : "Indore",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Madhya Pradesh",
               "short_name" : "MP",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Indore, Madhya Pradesh, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 22.8485735,
                  "lng" : 75.965395
               },
               "southwest" : {
                  "lat" : 22.6076326,
                  "lng" : 75.7411195
               }
            },
            "location" : {
               "lat" : 22.7195687,
               "lng" : 75.8577258
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 22.8485735,
                  "lng" : 75.965395
               },
               "southwest" : {
                  "lat" : 22.6076326,
                  "lng" : 75.7411195
               }
            }
         },
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

you can do also as follows

public  void getLatLongFromGivenAddress(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();
            }
        }
    }
Jitesh Upadhyay
  • 5,244
  • 2
  • 25
  • 43
0

So far all the answers seems valid, using either the geocode API or the Geocoder object, just wanted to point you towards this: Google Geocoder service is unavaliable (Coordinates to address)

I do not know how frequent this problem occurs but from time to time some devices cannot use the Geocoder object, so what I did was combining both methods, falling back to the HTTP geocode API.

Happy coding

Community
  • 1
  • 1
cYrixmorten
  • 7,110
  • 3
  • 25
  • 33
-1

Just use the following code and you will get what you want:

Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(ctx, Locale.getDefault());
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

Where 1 is the limit to get the maxResults.

jitain sharma
  • 584
  • 5
  • 19