There are many scenarios in Android development when you need GPS location, address and what not in your android application. For all theses android had provided many things like google Maps library, Geocoder etc. But if you need is the smallest one then using a full fledged library for it. So here we will discuss how can we get the longitude and latitude of an address from address string with the help of a simple google map API. It is the simplest and most effective way as it doesn’t need us to add the library only one API will do it.
So lets start, firstly by overriding the toString() method for our own Address.java model so that we can get the address in string representation.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Override public String toString() { StringBuilder addressStringBuilder = new StringBuilder(); addressStringBuilder.append(getAddressLine1()); if(getAddressLine2() != null) { addressStringBuilder.append(", ").append(getAddressLine2()); } addressStringBuilder.append(", ").append(getCity()); addressStringBuilder.append(", ").append(getState()); addressStringBuilder.append(", ").append(getCountry()); addressStringBuilder.append("- ").append(getPostCode()); return addressStringBuilder.toString(); } |
Now as we have the Address object converted to string, lets move on to our next and final step i.e. getting longitude and latitude from this address.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public void getLongitudeLatitude(Address address) { String addressString = address.toString(); addressString = addressString.replace(" ","+"); try { StringRequest request = new StringRequest(Request.Method.POST, "http://maps.google.com/maps/api/geocode/json?address="+addressString+"&sensor=false", new Response.Listener<String>() { @Override public void onResponse(String Response) { jsonObject = new JSONObject); try { JSONObject resultJSON = new JSONObject(Response); String longitute = resultJSON.get("results").getJSONObject(0) .getJSONObject("geometry").getJSONObject("location").getDouble("lng"); String latitude = resultJSON.get("results").getJSONObject(0).getJSONObject("geometry") .getJSONObject("location").getDouble("lat"); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError e) { e.printStackTrace(); } }); Volley.getInstance(this).addToRequestQueue(request); } |