-1

I have been looking for the answer everywhere but haven't been able to find it. I am wondering how I could convert a AutoComplete textbox address obtained from google maps api into latitude and longitude

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
  { 
        View v = inflater.inflate(R.layout.fragment_image, container, false);    
    AutoCompleteTextView location= (AutoCompleteTextView)v.findViewById(R.id.location);
    location.setAdapter(new PlacesAutoCompleteAdapter(getActivity(),R.layout.list_layout));
        String address=((AutoCompleteTextView)v.findViewById(R.id.location)).getText().toString();
        Geocoder geoCoder = new Geocoder(getActivity(), Locale.getDefault());

  }

PlacesAutoCompleteAdapter:

package com.example.makemyday;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;

    public class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements Filterable 
    {

        //private static final String PLACES_API_BASE="http://maps.googleapis.com/maps/api/place/json?sensor=false&address=Amsterdam&language=nl";
        private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
        private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
        private static final String OUT_JSON = "/json";
        //do not change this key
        private static final String API_KEY = "AIzaSyBXJwI8nszmYepuyNNUjx0Tl6pie2CEBfw";
        private static final String TAG = "CameraModule";

        private ArrayList<String> resultList;

        public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
            super(context, textViewResourceId);
        }

        @Override
        public int getCount() {
            return resultList.size();
        }

        @Override
        public String getItem(int index) {
            return resultList.get(index);
        }

        public ArrayList<String> autocomplete(String input) {

            ArrayList<String> resultList = null;
            StringBuilder jsonResults = new StringBuilder();
            HttpURLConnection conn = null;
            try {           
                StringBuilder sb = new StringBuilder(PLACES_API_BASE
                        + TYPE_AUTOCOMPLETE + OUT_JSON);
                sb.append("?sensor=true&key=" + API_KEY);
                //sb.append("&components=country:us");
                sb.append("&input=" + URLEncoder.encode(input, "utf8"));

                URL url = new URL(sb.toString());
                conn = (HttpURLConnection) url.openConnection();
                InputStreamReader in = new InputStreamReader(conn.getInputStream());
                // Load the results into a StringBuilder
                int read;
                char[] buff = new char[1024];
                while ((read = in.read(buff)) != -1) {
                    jsonResults.append(buff, 0, read);
                }
            } catch (MalformedURLException e) {
                Log.e(TAG, "Error processing Places API URL", e);
                return resultList;
            } catch (IOException e) {
                Log.e(TAG, "Error connecting to Places API", e);
                return resultList;
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }

            try {
                // Create a JSON object hierarchy from the results
                JSONObject jsonObj = new JSONObject(jsonResults.toString());

                JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
                // Extract the Place descriptions from the results
                resultList = new ArrayList<String>(predsJsonArray.length());
                for (int i = 0; i < predsJsonArray.length(); i++) {
                    resultList.add(predsJsonArray.getJSONObject(i).getString(
                            "description"));
                }

            } catch (JSONException e) {
                Log.e(TAG, "Cannot process JSON results", e);
            }

            return resultList;
        }

        @Override
        public Filter getFilter() {
            Filter filter = new Filter() {
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    FilterResults filterResults = new FilterResults();
                    if (constraint != null) {
                        // Retrieve the autocomplete results.

                        resultList = autocomplete(constraint
                                .toString());

                        // Assign the data to the FilterResults
                        filterResults.values = resultList;
                        filterResults.count = resultList.size();
                    }
                    return filterResults;
                }

                @Override
                protected void publishResults(CharSequence constraint,
                        FilterResults results) {
                    if (results != null && results.count > 0) {
                        notifyDataSetChanged();
                    } else {
                        notifyDataSetInvalidated();
                    }
                }
            };
            return filter;
        }
    }

I want to convert location to its corresponding latitude longitude. I could find several threads on converting Address to latitude longitude, bt not on how i could build an address from a string object

gazubi
  • 561
  • 8
  • 32

1 Answers1

1

The answer is called Geocoding which will be available in the maps api. You should post what you have tried and your PlacesAutoCompleteAdapter.

This answer which is copied form another answer you would have found had you searched, should solve your issue:

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

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

}
Community
  • 1
  • 1
Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124
  • I tried to look and found ways to convert address to latitude longitude as shown http://stackoverflow.com/questions/3574644/how-can-i-find-the-latitude-and-longitude-from-address. Thanks for your answer anyway. I've edited mine already – gazubi Feb 23 '14 at 01:06
  • In response to your edit - what does your string object contain? You see the maps api treats a string as a location/address so there should be no need to build an address as you've staed, unless I'm missing something? (addresses are just in the form "location, broader location, broader location" eg: "london, england, uk") – Nick Cardoso Feb 23 '14 at 01:08
  • my string object gets an address from google map api. SO it's like an autocomplete box, where when the user types the first few letters of the address, he is prompted with a bunch of addresses to choose from. So typically it would be an address string returned by google maps api v2 – gazubi Feb 23 '14 at 01:11
  • Ok, so why can't you geocode this back again? Or why not request latlng in the first instance? – Nick Cardoso Feb 23 '14 at 01:11
  • yes. allthough i get the address string, I don't know hw I could convert a string to obtain latitude longitude – gazubi Feb 23 '14 at 01:12
  • With the method I have posted above – Nick Cardoso Feb 23 '14 at 01:12
  • I am quite new to android, and not really sure how to request latlng in the first instance – gazubi Feb 23 '14 at 01:12
  • yes trying your method but also wondering if there was a better way to do this – gazubi Feb 23 '14 at 01:13
  • I'm about to go to bed so can't help you further tonight but I've used the javascript verions of their API and you can ask for latlng as the result instead of the address or along with the address , so your best bet is to look at the google maps docs which usually arent terrible – Nick Cardoso Feb 23 '14 at 01:16