2014-02-23 26 views
-1

我一直在尋找答案,但一直未能找到它。我想知道我怎麼會從谷歌地圖API獲得一個自動完成文本框的地址轉換爲緯度和經度將字符串轉換爲緯度經度android

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

我想要的位置轉換到其相應的經緯度。我可以找到幾個線程將Address轉換爲緯度經度,但不是我如何從一個字符串對象構建地址

回答

1

答案被稱爲Geocoding這將在地圖api中可用。您應該發佈您嘗試過的內容和您的PlacesAutoCompleteAdapter。

這個答案被複制形式another answer,你會發現有您搜索,應該能夠解決您的問題:

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

} 
+0

我試圖尋找和發現的方法來轉換地址,經緯度如圖所示的http://計算器.COM /問題/ 3574644 /何燦我找到的最緯度和經度從地址。無論如何感謝您的回答。我已經編輯了我的 – gazubi

+0

爲了響應你的編輯 - 你的字符串對象包含什麼?你會看到地圖API將字符串視爲位置/地址,所以不應該像你所預見的那樣建立一個地址,除非我錯過了某些東西? (地址的形式只是「位置,位置更廣,位置更寬」,例如:「倫敦,英格蘭,英國」) –

+0

我的字符串對象從google map api獲取地址。所以它就像一個自動完成框,當用戶鍵入地址的前幾個字母時,會提示他有一堆地址可供選擇。因此,通常它會是由google maps api v2 – gazubi