使用 Google Places Autocomplete API 时空间不工作

     2023-03-05     282

关键词:

【中文标题】使用 Google Places Autocomplete API 时空间不工作【英文标题】:Spaces Not Working While Using Google Places Autocomplete API 【发布时间】:2013-11-16 23:12:51 【问题描述】:

当我在我的 Android 应用中输入空格时,我的下拉菜单中不再显示任何结果。我怎样才能解决这个问题?我正在对输入进行编码,所以我不确定它为什么不起作用...

空格前:

空格后:

我查看了https://developers.google.com/places/documentation/autocomplete,但没有找到任何可以帮助我的东西。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.widget.AutoCompleteTextView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity 

    AutoCompleteTextView atvPlaces;
    PlacesTask placesTask;
    ParserTask parserTask;

    @Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    atvPlaces = (AutoCompleteTextView) findViewById(R.id.atv_places);
    atvPlaces.setThreshold(1);

    atvPlaces.addTextChangedListener(new TextWatcher() 

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) 
            placesTask = new PlacesTask();
            placesTask.execute(s.toString());
        

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
        int after) 
            // TODO Auto-generated method stub
        

        @Override
        public void afterTextChanged(Editable s) 
            // TODO Auto-generated method stub
        
    );


/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuffer sb = new StringBuffer();

        String line = "";
        while( ( line = br.readLine()) != null)
            sb.append(line);
        

        data = sb.toString();

        br.close();

    catch(Exception e)
        Log.d("Exception while downloading url", e.toString());
    finally
        iStream.close();
        urlConnection.disconnect();
    
    return data;


// Fetches all places from GooglePlaces AutoComplete Web Service
private class PlacesTask extends AsyncTask<String, Void, String>

    @Override
    protected String doInBackground(String... place) 
        // For storing data from web service 
        String data = "";

        // Obtain browser key from https://code.google.com/apis/console
        String key = "key=AIzaSyDcXFSC2I6ZqxQeAbUMFvJKMrA98217H9U";

        String input="";

        try 
            input = "input=" + URLEncoder.encode(place[0], "utf-8");
         catch (UnsupportedEncodingException e1) 
            e1.printStackTrace();
        

        // place type to be searched
        String types = "types=(regions)";

        // Sensor enabled
        String sensor = "sensor=false";

        // Building the parameters to the web service
        String parameters = input+"&"+types+"&"+sensor+"&"+key;

        // Output format
        String output = "json";

        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;

        try
            // Fetching the data from we service
            data = downloadUrl(url);
        catch(Exception e)
            Log.d("Background Task",e.toString());
        
        return data;
    

    @Override
    protected void onPostExecute(String result) 
        super.onPostExecute(result);

        // Creating ParserTask
        parserTask = new ParserTask();

        // Starting Parsing the JSON string returned by Web Service
        parserTask.execute(result);
    

/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>

    JSONObject jObject;

    @Override
    protected List<HashMap<String, String>> doInBackground(String... jsonData) 

        List<HashMap<String, String>> places = null;

        PlaceJSONParser placeJsonParser = new PlaceJSONParser();

        try
            jObject = new JSONObject(jsonData[0]);

            // Getting the parsed data as a List construct
            places = placeJsonParser.parse(jObject);

        catch(Exception e)
            Log.d("Exception",e.toString());
        
        return places;
    

    @Override
    protected void onPostExecute(List<HashMap<String, String>> result) 

        String[] from = new String[]  "description";
        int[] to = new int[]  android.R.id.text1 ;

        // Creating a SimpleAdapter for the AutoCompleteTextView
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);

        // Setting the adapter
        atvPlaces.setAdapter(adapter);
    


@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;


【问题讨论】:

是的,输入中可以有(编码的)空格。当您发现问题时,您使用的是什么输入值? @pushbit 只有当我输入空格时,下拉菜单才会消失,我不再得到任何输出。 @GreekOphion 你找到这个问题的解决方案了吗,我也参考了同一个教程并遇到了同样的问题 【参考方案1】:

我刚刚尝试了一些搜索结果:

https://maps.googleapis.com/maps/api/place/autocomplete/json?input=123+43+Sweden&types=%28regions%29&sensor=false&key=AIzaSyDcXFSC2I6ZqxQeAbUMFvJKMrA98217H9U

URL 编码可能没有正确编码空间。如果您在 get 中有类似“123+”的内容,它应该会产生如上所示的有效结果。相反,您需要进行替换以将空格替换为 +。

input=input.replace(" ","+");

尝试在 URLEncoder 之后保留编码,但消除 + 被编码的任何风险。

HTH

【讨论】:

试过这个并没有改变任何东西。 您能否调试并确保您的 PlacesTask 中的 URL 看起来像 input=123+... 并调试 downloadUrl()HttpURLConnection 中的 URL 以确保它保持不变相同的格式? 编辑了我的答案以更新编码。基本上确保您发送到HttpURLConnection 的最终 URL 的输入地址使用+而不是空格。如果是这种情况,请尝试浏览器中的 URL 并查看您得到的预测。如果它适用于浏览器而不是应用程序,则AutoCompleteTextView 可能是问题所在。 @sturrockad Locatehttps://maps.googleapis.com/maps/api/place/autocomplete/json?input=Sector+24&types=geocode&sensor=false&key=AIzaSyDo_9RsCh1Hlw1LgNjEdyf3HPyZ76PE0eY 这是我的数据,但空间仍在停止建议 添加 adapter.notifyDataSetChanged();这对我有用【参考方案2】:

尝试添加

adapter.notifyDataSetChanged();

之后

atvPlaces.setAdapter(adapter);

【讨论】:

这修复了它。谢谢。【参考方案3】:

试试“。”而不是空间。你应该用 dot(.) 替换空格,如果它不起作用你应该像在 ubuntu 中一样尝试“\”。可能有用

【讨论】:

【参考方案4】:

尝试替换这一行

        input = "input=" + URLEncoder.encode(place[0], "utf-8");

通过

        input = "input=" + URLEncoder.encode(place[0]);

【讨论】:

【参考方案5】:

我喜欢一个解决方案,TextWatcher() 没有任何问题。

需要使用下面的代码 在下面的代码中,我没有覆盖“performFiltering”方法,我添加了它,我的自动完成文本框现在工作正常。

公共类 CustomAutoCompleteView 扩展 AutoCompleteTextView

public CustomAutoCompleteView(Context context)   
    super(context);  
    // TODO Auto-generated constructor stub  
  

public CustomAutoCompleteView(Context context, AttributeSet attrs)   
    super(context, attrs);  
    // TODO Auto-generated constructor stub  
  

public CustomAutoCompleteView(Context context, AttributeSet attrs,  
        int defStyle)   
    super(context, attrs, defStyle);  
    // TODO Auto-generated constructor stub  
  

@Override  
protected void performFiltering(final CharSequence text, final int keyCode)   
    String filterText = "";  
    super.performFiltering(filterText, keyCode);  
  
/** 
* After a selection, capture the new value and append to the existing 
* text 
*/  
@Override  
protected void replaceText(final CharSequence text)   
    super.replaceText(text);  
  

【讨论】:

使用 GooglePlacesAutocompleteWidget 时强制 flutter_google_places 仅显示城市

】使用GooglePlacesAutocompleteWidget时强制flutter_google_places仅显示城市【英文标题】:Forceflutter_google_placestoonlydisplaycitieswhenusingGooglePlacesAutocompleteWidget【发布时间】:2020-04-0308:15:49【问题描述】:我正在使用flutter_google_places小部件搜索... 查看详情

使用 google-places-api 的简单 html 页面的 ApiNotActivatedMapError

】使用google-places-api的简单html页面的ApiNotActivatedMapError【英文标题】:ApiNotActivatedMapErrorforsimplehtmlpageusinggoogle-places-api【发布时间】:2016-06-1212:42:16【问题描述】:我正在尝试创建一个包含google-places-api的简单html页面(稍后我想... 查看详情

google.maps.places.Autocomplete 语言输出

...output【发布时间】:2015-03-2316:26:29【问题描述】:我正在使用google.maps.places.Autocomplete对象并且总是以乌克兰语获得结果。我正在加载这样的库http://maps.google.com/maps/api/js?sens 查看详情

使用 Google Places API 获得 20 多个结果

】使用GooglePlacesAPI获得20多个结果【英文标题】:Obtainingmorethan20resultswithGooglePlacesAPI【发布时间】:2011-10-2109:43:48【问题描述】:我想开发一个地图应用程序,它会显示给定地点附近的银行。我使用Places库进行搜索,每次它只返... 查看详情

使用 Google PLACES Api 搜索查看自动完成建议

】使用GooglePLACESApi搜索查看自动完成建议【英文标题】:SearchViewAutocompletesuggestionsusingGooglePLACESApi【发布时间】:2020-07-0701:52:51【问题描述】:@OverridepublicbooleanonCreateOptionsMenu(Menumenu)super.onCreateOptionsMenu(menu);this.menu=menu;Me 查看详情

Google Places API:如何使用多种类型?

】GooglePlacesAPI:如何使用多种类型?【英文标题】:GooglePlacesAPI:Howtousemultipletypes?【发布时间】:2015-10-1523:41:19【问题描述】:我需要一个POIAPI来返回评分、照片、打开/关闭时间等,我认为GooglePlacesAPI似乎可以满足我的要求,但... 查看详情

反应:Google Places API/ Places 详细信息

...期组件。目前,我无法设置状态并正确绑定对象。我可以使用一些帮助来了解我的逻辑失败的地方。exportdefault 查看详情

google.maps.places.Autocomplete 本地化

...】:2013-08-3016:54:30【问题描述】:在我的应用程序中,我使用google.maps.places.Autocomplete.getPlace()来获取城市名称等信息,问题是检索到的信息是根据导入库时通过查询字符串传递的“language”参数 查看详情

Google Places API,获取用户地址

...发布时间】:2015-12-3023:53:11【问题描述】:我一直在努力使用GooglePlacesAPI,我需要使用AddressAPI。我使用autoComplete和placePickerAPI很好,但由于某种原因AddressAPI无法正常工作。我已经尝试过查看这个https://developers. 查看详情

Google Places API,使用邮政编码自动完成

】GooglePlacesAPI,使用邮政编码自动完成【英文标题】:GoogleplacesAPI,autocompletewithpostalcode【发布时间】:2014-09-0208:29:59【问题描述】:所以我正在尝试使用城市(在比利时)实现AutoCompleteTextView。这是我调用的网址:https://maps.google... 查看详情

Google 地图 - Facebook Places 使用 JSON 的虚假位置

】Google地图-FacebookPlaces使用JSON的虚假位置【英文标题】:Googlemaps-FacebookPlacesfakelocationusingJSON【发布时间】:2011-07-1013:01:54【问题描述】:我正在对基于位置的社交网络进行一些研究,并试图通过修改google返回到Firefox浏览器的JSO... 查看详情

如何使用 React 和 Google Places API 在 Google 地图上显示地点标记?

】如何使用React和GooglePlacesAPI在Google地图上显示地点标记?【英文标题】:HowcanIuseReactwithGooglePlacesAPI,todisplayplacemarkersonaGooglemap?【发布时间】:2018-04-1706:31:10【问题描述】:我正在尝试构建与onAirbnb类似的地图,您可以在其中拖... 查看详情

Google Places API 错误

...【发布时间】:2012-03-0320:00:49【问题描述】:我正在尝试使用GooglePlacesAPI请求伦敦市中心半径1000米内的所有地点,所需的输出类型是XML。这是我使用JQuery的代码:<!DOCTYPEhtml><html><head><scriptsrc="http://code.jq 查看详情

如何使用 CORS 实现 JavaScript Google Places API 请求

】如何使用CORS实现JavaScriptGooglePlacesAPI请求【英文标题】:HowtouseCORStoimplementJavaScriptGooglePlacesAPIrequest【发布时间】:2017-06-3001:33:47【问题描述】:我真的不明白我应该如何完成这项工作:varrequestURL=\'https://maps.googleapis.com/maps/api/p... 查看详情

使用 Google Places API 时的 REQUEST_DENIED

】使用GooglePlacesAPI时的REQUEST_DENIED【英文标题】:REQUEST_DENIEDwhenusingtheGooglePlacesAPI【发布时间】:2012-01-1517:05:06【问题描述】:我正在尝试使用以下网址向GooglePlacesAPI发出请求:https://maps.googleapis.com/maps/api/place/search/xml?location=37.77... 查看详情

在 UICollectionViewCell 中使用 UITableView(模仿 Google Places 底部滚动列表)

】在UICollectionViewCell中使用UITableView(模仿GooglePlaces底部滚动列表)【英文标题】:WorkingwithUITableViewinsideUICollectionViewCell(MimicGooglePlacesBottomScrollingList)【发布时间】:2017-09-2000:01:57【问题描述】:我正在尝试模仿谷歌位置底部滚动... 查看详情

使用 Google Places Autocomplete API 时空间不工作

】使用GooglePlacesAutocompleteAPI时空间不工作【英文标题】:SpacesNotWorkingWhileUsingGooglePlacesAutocompleteAPI【发布时间】:2013-11-1623:12:51【问题描述】:当我在我的Android应用中输入空格时,我的下拉菜单中不再显示任何结果。我怎样才能... 查看详情

从 Google Places API 获取地址信息

...1-09-2317:57:38【问题描述】:我一直希望在我的一个项目中使用GooglePlacesAPI,但我有一个我无法弄清楚的问题。应该很简单,但我无法完全理解它。这是我的问题:我正在尝试实现一个使用Google地方信息查找位置的自动完成字段,... 查看详情