我可以在Android上的自动完成文本视图中获取google place api。我收到了一个完整的地址字符串,虽然有时只是地址的一部分。我遇到的问题是将它们分成不同领域的部分,例如。地址字段,郊区字段,城市字段和邮政编码字段。
这是google place api的回复:
{
"predictions" : [
{
"description" : "3 Manukau Road, Auckland, New Zealand",
"id" : "a24a80c787ac6c9dc971d38bb3bdf51beeeda5ea",
"matched_substrings" : [
{
"length" : 1,
"offset" : 0
},
{
"length" : 2,
"offset" : 2
}
],
"place_id" : "ChIJy_mQFnlIDW0R9RdXsdgg3XA",
"reference" : "CkQ9AAAAkIlLFVaSq2FE1r8HEdxpQBKEb59YR9hxN_-tEzmijuMMVSpypMAkv6FK4THBBWXzhfX_jHtGh5XOUAliu1u6jRIQxZ_Lk8k3QRzd5fUBTEIr4RoUnF8fs8cqbqTnpYafr0HSUwgdrY8",
"terms" : [
{
"offset" : 0,
"value" : "3"
},
{
"offset" : 2,
"value" : "Manukau Road"
},
{
"offset" : 16,
"value" : "Auckland"
},
{
"offset" : 26,
"value" : "New Zealand"
}
],
"types" : [ "street_address", "geocode" ]
},
{
"description" : "3 Marua Road, Auckland, New Zealand",
"id" : "20b196feed1d9e6d4bfac4d8ec9b1e6b1ea203e8",
"matched_substrings" : [
{
"length" : 1,
"offset" : 0
},
{
"length" : 2,
"offset" : 2
}
],
"place_id" : "ChIJA_ht6P1IDW0RApaaeTK9YQg",
"reference" : "CkQ7AAAATstfIxOFji-XgcO65HOmIZqzbGbCsiFASrTOLf2tvR8BEaslOoYvhYzXEST8A7TLdM6C0oawX0RtTAHYBSYfXxIQNYzucT3x_S5cgApq1X5X2hoURmzbbROwm92iH4LZ0cdcHKLkHOQ",
"terms" : [
{
"offset" : 0,
"value" : "3"
},
{
"offset" : 2,
"value" : "Marua Road"
},
{
"offset" : 14,
"value" : "Auckland"
},
{
"offset" : 24,
"value" : "New Zealand"
}
],
"types" : [ "street_address", "geocode" ]
},
{
"description" : "3 Madeira Lane, Auckland, New Zealand",
"id" : "c8cd18ee12af4113a181977b004d0ecee2ea4ca1",
"matched_substrings" : [
{
"length" : 1,
"offset" : 0
},
{
"length" : 2,
"offset" : 2
}
],
"place_id" : "ChIJWw8d29xHDW0R9wfEOBhFSig",
"reference" : "CkQ9AAAAlz1AJfcAIMkaCF-Yz2QZgwgaEaIvysVdxpagytcacVXb6ftBzUvW09_gxy1nfAGeHEvxDMJICLlEWAqaKOOmShIQ9h_pqF6BbIAXnP7WvsTwJBoU10394ImzJpuRFUkOFfPZjTu0QKE",
"terms" : [
{
"offset" : 0,
"value" : "3"
},
{
"offset" : 2,
"value" : "Madeira Lane"
},
{
"offset" : 16,
"value" : "Auckland"
},
{
"offset" : 26,
"value" : "New Zealand"
}
],
"types" : [ "street_address", "geocode" ]
}
],
"status" : "OK"
}
答案 0 :(得分:0)
这是我使用android实现自动完成视图并处理JSON的方式。
public class DestinationCity extends SherlockActivity implements OnItemClickListener {
private static final String LOG_TAG = "Google Places Autocomplete";
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";
private static final String API_KEY = "<--Your API Key-->";
AutoCompleteTextView autoCompView;
TextView selectDestination;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_destination_city);
initViewS();
}
private void initViewS(){
mActionBar();
autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));
autoCompView.setOnItemClickListener(DestinationCity.this);
selectDestination = (TextView)findViewById(R.id.selectDestination);
selectDestination.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(city.equals("")||city == null) {
Toast.makeText(DestinationCity.this,"Please enter destination",Toast.LENGTH_LONG).show();
}
else{
Intent result = new Intent("RESULT_ACTION");
result.putExtra("select_city", city);
setResult(Activity.RESULT_OK, result);
finish();
}
}
});
}
private void mActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowCustomEnabled(false);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
SpannableString sTitle = new SpannableString("xxyyzz");
sTitle.setSpan(new CustomTypeFace(getApplicationContext(), CabLibrary.TITLE_FONT, getResources().getDimension(R.dimen.size22)),
0, sTitle.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
actionBar.setTitle(sTitle);
actionBar.setLogo(getResources().getDrawable(R.drawable.logo));
}
class GooglePlacesAutocompleteAdapter extends ArrayAdapter implements Filterable {
private ArrayList<String> resultList;
public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
@Override
public int getCount() {
return resultList.size();
}
@Override
public String getItem(int index) {
return resultList.get(index);
}
@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;
}
}
String city = "";
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
String str = (String) adapterView.getItemAtPosition(position);
city = str;
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
public static ArrayList autocomplete(String input) {
ArrayList resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&components=country:in");
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
Log.d("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.d("Places API URL", e.toString());
return resultList;
} catch (IOException e) {
Log.d("Error to Places API", e.toString());
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
Log.d("JsonResult",jsonResults.toString());
// 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(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
System.out.println("============================================================");
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
Log.d("Description",predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
Log.d("Hson Result", e.toString());
}
return resultList;
}
}
和这两者的XML是:
&LT;
?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DestinationCity">
<RelativeLayout
android:layout_alignParentTop="true"
android:id="@+id/search_container"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:background="@drawable/grey_button_border"
android:orientation="horizontal" >
<AutoCompleteTextView
android:paddingLeft="10dp"
android:id="@+id/autoCompleteTextView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_toLeftOf="@+id/search_button"
android:background="@color/grey"
android:cursorVisible="true"
android:gravity="center_vertical|left"
android:hint="@string/cities_search_hint"
android:imeOptions="actionDone"
android:inputType="text"
android:maxLines="1"
android:textColor="@color/font_color"
android:textSize="@dimen/size16"
android:textStyle="bold" >
<requestFocus />
</AutoCompleteTextView>
</RelativeLayout>
</RelativeLayout>