Google Places API 自动完成仅获取城市列表

2024-01-03

我正在我的 Android 应用程序上实现谷歌的地点自动完成功能,它正在工作,显示每个相似的地点,但是只有当用户尝试搜索任何内容时,我如何才能获得城市建议。

我搜索了很多,但找不到 Android 地点自动完成的类似问题。

我已经从谷歌的示例中实现了 PlaceAutocompleteAdapter ,它看起来像这样

放置自动完成适配器

package com.tribikram.smartcitytraveler;

import android.content.Context;
import android.graphics.Typeface;
import android.text.style.CharacterStyle;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.data.DataBufferUtils;
import com.google.android.gms.location.places.AutocompleteFilter;
import com.google.android.gms.location.places.AutocompletePrediction;
import com.google.android.gms.location.places.AutocompletePredictionBufferResponse;
import com.google.android.gms.location.places.GeoDataClient;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.tasks.RuntimeExecutionException;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Adapter that handles Autocomplete requests from the Places Geo Data Client.
 * {@link AutocompletePrediction} results from the API are frozen and stored directly in this
 * adapter. (See {@link AutocompletePrediction#freeze()}.)
 */
public class PlaceAutocompleteAdapter
        extends ArrayAdapter<AutocompletePrediction> implements Filterable {

    private static final String TAG = "PlaceACA";
    private static final CharacterStyle STYLE_BOLD = new StyleSpan(Typeface.BOLD);
    /**
     * Current results returned by this adapter.
     */
    private ArrayList<AutocompletePrediction> mResultList;

    /**
     * Handles autocomplete requests.
     */
    private GeoDataClient mGeoDataClient;

    /**
     * The bounds used for Places Geo Data autocomplete API requests.
     */
    private LatLngBounds mBounds;

    /**
     * The autocomplete filter used to restrict queries to a specific set of place types.
     */
    private AutocompleteFilter mPlaceFilter;

    /**
     * Initializes with a resource for text rows and autocomplete query bounds.
     *
     * @see android.widget.ArrayAdapter#ArrayAdapter(android.content.Context, int)
     */
    public PlaceAutocompleteAdapter(Context context, GeoDataClient geoDataClient,
                                    LatLngBounds bounds, AutocompleteFilter filter) {
        super(context, android.R.layout.simple_expandable_list_item_2, android.R.id.text1);
        mGeoDataClient = geoDataClient;
        mBounds = bounds;
        mPlaceFilter = filter;
    }

    /**
     * Sets the bounds for all subsequent queries.
     */
    public void setBounds(LatLngBounds bounds) {
        mBounds = bounds;
    }

    /**
     * Returns the number of results received in the last autocomplete query.
     */
    @Override
    public int getCount() {
        return mResultList.size();
    }

    /**
     * Returns an item from the last autocomplete query.
     */
    @Override
    public AutocompletePrediction getItem(int position) {
        return mResultList.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = super.getView(position, convertView, parent);

        // Sets the primary and secondary text for a row.
        // Note that getPrimaryText() and getSecondaryText() return a CharSequence that may contain
        // styling based on the given CharacterStyle.

        AutocompletePrediction item = getItem(position);

        TextView textView1 = (TextView) row.findViewById(android.R.id.text1);
        TextView textView2 = (TextView) row.findViewById(android.R.id.text2);
        textView1.setText(item.getPrimaryText(STYLE_BOLD));
        textView2.setText(item.getSecondaryText(STYLE_BOLD));

        return row;
    }

    /**
     * Returns the filter for the current set of autocomplete results.
     */
    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();

                // We need a separate list to store the results, since
                // this is run asynchronously.
                ArrayList<AutocompletePrediction> filterData = new ArrayList<>();

                // Skip the autocomplete query if no constraints are given.
                if (constraint != null) {
                    // Query the autocomplete API for the (constraint) search string.
                    filterData = getAutocomplete(constraint);
                }

                results.values = filterData;
                if (filterData != null) {
                    results.count = filterData.size();
                } else {
                    results.count = 0;
                }

                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                if (results != null && results.count > 0) {
                    // The API returned at least one result, update the data.
                    mResultList = (ArrayList<AutocompletePrediction>) results.values;
                    notifyDataSetChanged();
                } else {
                    // The API did not return any results, invalidate the data set.
                    notifyDataSetInvalidated();
                }
            }

            @Override
            public CharSequence convertResultToString(Object resultValue) {
                // Override this method to display a readable result in the AutocompleteTextView
                // when clicked.
                if (resultValue instanceof AutocompletePrediction) {
                    return ((AutocompletePrediction) resultValue).getFullText(null);
                } else {
                    return super.convertResultToString(resultValue);
                }
            }
        };
    }

    /**
     * Submits an autocomplete query to the Places Geo Data Autocomplete API.
     * Results are returned as frozen AutocompletePrediction objects, ready to be cached.
     * Returns an empty list if no results were found.
     * Returns null if the API client is not available or the query did not complete
     * successfully.
     * This method MUST be called off the main UI thread, as it will block until data is returned
     * from the API, which may include a network request.
     *
     * @param constraint Autocomplete query string
     * @return Results from the autocomplete API or null if the query was not successful.
     * @see GeoDataClient#getAutocompletePredictions(String, LatLngBounds, AutocompleteFilter)
     * @see AutocompletePrediction#freeze()
     */
    private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) {
        Log.i(TAG, "Starting autocomplete query for: " + constraint);

        // Submit the query to the autocomplete API and retrieve a PendingResult that will
        // contain the results when the query completes.
        Task<AutocompletePredictionBufferResponse> results =
                mGeoDataClient.getAutocompletePredictions(constraint.toString(), mBounds,
                        mPlaceFilter);

        // This method should have been called off the main UI thread. Block and wait for at most
        // 60s for a result from the API.
        try {
            Tasks.await(results, 60, TimeUnit.SECONDS);
        } catch (ExecutionException | InterruptedException | TimeoutException e) {
            e.printStackTrace();
        }

        try {
            AutocompletePredictionBufferResponse autocompletePredictions = results.getResult();

            Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
                    + " predictions.");

            // Freeze the results immutable representation that can be stored safely.
            return DataBufferUtils.freezeAndClose(autocompletePredictions);
        } catch (RuntimeExecutionException e) {
            // If the query did not complete successfully return null
            Toast.makeText(getContext(), "Error contacting API: " + e.toString(),
                    Toast.LENGTH_SHORT).show();
            Log.e(TAG, "Error getting autocomplete prediction API call", e);
            return null;
        }
    }
}

我是初学者,如果您发现任何错误,请指出。那将是很大的帮助。 谢谢你!


您可以使用地点自动完成通过谷歌

Step 1:-

在谷歌开发者帐户中添加一个项目并从那里获取密钥

示例代码

Step 2:-

添加渐变

 implementation 'com.google.android.gms:play-services-places:9.6.0'

或最新版本

implementation 'com.google.android.gms:play-services-places:latest_version'

Step 3:-

在清单文件中添加此标签

<meta-data android:name="com.google.android.geo.API_KEY" android:value="Your api key"/>

Step 4:-

现在实现您的片段或活动类PlaceSelectionListener像这样

public class Fragment_Profile extends Fragment implements View.OnClickListener, PlaceSelectionListener

声明这个变量

private static final int REQUEST_SELECT_PLACE = 1000;

然后最后点击按钮调用这个

try {
                    AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
                            .setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES)
                            .build();
                    Intent intent = new PlaceAutocomplete.IntentBuilder
                            (PlaceAutocomplete.MODE_FULLSCREEN)
                            .setFilter(typeFilter)
                            .build(getActivity());
                    startActivityForResult(intent, REQUEST_SELECT_PLACE);
                } catch (GooglePlayServicesRepairableException |
                        GooglePlayServicesNotAvailableException e) {
                    e.printStackTrace();
                }

这就是您正在寻找的过滤器

自动完成过滤器.TYPE_FILTER_CITIES

然后在重写的方法中获取选定的值

 @Override
    public void onPlaceSelected(Place place) {
        Log.i("Selected", "Place Selected: " + place.getAddress());

    }

您可以从这里查看文档https://developers.google.com/places/android-sdk/autocomplete https://developers.google.com/places/android-sdk/autocomplete and http://codesfor.in/android-places-autocomplete-example/ http://codesfor.in/android-places-autocomplete-example/

Thanks

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Google Places API 自动完成仅获取城市列表 的相关文章

  • 如何在Android中添加水平滚动视图和列表视图

    我正在尝试创建一个应用程序 因为我需要创建一个列表视图 但最重要的是我想要一个用于多个数据的水平列表视图 我很困惑我们该如何做到这一点 请帮助我 主要活动 XML
  • 如何为整个 Android 应用程序设置默认字体系列

    我在我的应用程序中使用 Roboto 浅色字体 要设置字体 我必须添加android fontFamily sans serif light 到每一个视图 有没有办法将 Roboto 字体声明为整个应用程序的默认字体系列 我已经尝试过这样的
  • EditText - 在键入时更改文本

    我需要在输入时替换 EditText 内的文本 示例 如果用户按下 A 它将被存储到缓冲区中 并在 EditText 上显示 D 看起来像是按下了 D 现在我可以读取按下的字符 但无法显示 et 中的任何字符以避免 stackoverflo
  • Android 应用内购买

    我正在尝试开发一个停车应用程序 用户可以在其中为停车时间付费 我浏览了这份文件应用内产品 http developer android com google play billing billing overview html produc
  • 使用 noHistory="true" 和/或 showOnLockScreen="true" 向 Activity 请求 Android M 权限

    我正在开发一个视频通话应用程序 并且有一个 来电 屏幕 当有人打电话给用户时 它会提醒用户 此屏幕是由传入 GCM 触发的活动 并且在清单中设置了 noHistory true 和 showOnLockScreen true 以便用户无需解
  • Android Volley 服务器错误

    I am posting data all strings to varchar variables in server but i am getting volley server error or badnetwork performa
  • 如何从 AccountManager.getAccounts() 获取与特定帐户关联的图标

    每个帐户的帐户设置中都会显示一个图标 对于 Google 帐户有一个图标 对于 Facebook 帐户有另一个图标 有没有办法从应用程序的代码中获取该图标 最后我解决了 private Drawable getIconForAccount
  • 如何在ionic框架+ angularjs中调用函数?

    我正在使用 ionic 框架来制作 android 应用程序 我有 cordova5 1版本 first 我使用命令行创建一个项目ionic 启动 myApp 选项卡 我添加了android平台 现在我需要将java代码与javascrip
  • android-透明RelativeLayout

    我想要制作一个具有可绘制渐变作为背景的活动 并将在其背景顶部显示 4 个面板 相对布局 现在我想让 4 个面板透明 例如 50 以便也可以看到渐变背景 我搜索了谷歌 但我发现只能通过活动而不是布局来做到这一点 如何做我想做的事 您可以创建一
  • 如何使用抽屉布局左侧移动主要内容

    刚刚检查了如何使用 DrawerLayout 制作菜单here http www androidhive info 2013 11 android sliding menu using navigation drawer 但左侧菜单正在移动
  • Android 背景 + 文本 + 按钮图标

    我想要一个图像设置为文本的背景 并在文本的左侧设置一个图标 在iPhone中非常简单 但不知道如何在Android上做到这一点 调整按钮的大小并保持图标 文本的位置和距离正确 iPhone 安卓我有这个 xml代码是
  • listItems之间的黑线,如何删除?

    我的列表项之间有一些水平黑线 如何删除它们 我的图形没有一部分 谢谢 listview setDivider null listview setDividerHeight 0 或在 XML 中
  • Apache POI 的 ProGuard 设置

    我正在构建一个使用 Apache POI 库的应用程序 当我调试应用程序 在不运行 Proguard 的情况下编译它 时 一切都运行良好 但是在导出 APK 后 当我运行应用程序并打开 Excel 文件时 出现以下异常 RuntimeExc
  • 还有其他地方可以获得 google-services.json 吗?

    我尝试单击GET A CONFIGURATION FILE链接自the docs https developers google com identity sign in android start integrating get conf
  • 如何将 Facebook App 的 accessToken 添加到 GraphRequest.newGraphPathRequest 方法? [复制]

    这个问题在这里已经有答案了 我复制了下面的代码Facebook Graph Api console 但是 Android Studio 无法识别accessToken 我已经创建了一个Facebook App我得到了它acesstoken
  • 如何在Android中将字体粗细设置为细、常规

    我有 3 个文本视图 我需要将它们的粗细设置为 轻 常规 和 压缩 有人可以帮助我如何在 Android 中实现这一目标吗 Use android textStyle on a TextView设置文本样式 例如bold italic或正常
  • 使用 Android 2.x 进行实时音频流传输

    我需要在 2 x 及更高版本的设备上播放直播 This http developer android com guide appendix media formats html声明不可能在 Android 2 x 的设备上播放直播 我在这里
  • 如何等待 Kotlin 协程完成

    我读过几十篇文章 但不知何故 没有一个答案似乎适用于我的情况 我想要实现的是在Fragment中等待ViewModel使用Room执行操作 Dao Query SELECT FROM my table WHERE id id suspend
  • 是否可以从 Android Studio 恢复被覆盖的文件?

    由于错误 我覆盖了我的两个来自 android studio 的具有相同名称的项目 并且今天我已经取消了该操作 我尝试打开主项目 但发现其中没有 Java 类 只有布局文件 在我覆盖的第二个项目中 文件存在巨大混乱 并尝试使用 Androi
  • Android Nougat 无法显示某些矢量文件 (Resources$NotFoundException)

    我一直在开发一个包含许多矢量图形的应用程序 最近我开始在 Nougat 上测试它 发现它立即崩溃了 logcat 在加载矢量时显示 Resources NotFoundException 这让人想起带有矢量图形的 Android 早期版本中

随机推荐

  • 信用卡/借记卡号是数字还是整数?

    由于数字也可以是小数 这让我认为 CC 数字应该是整数 这是有道理的 因为我认为没有任何信用卡以 0 开头 而且它们都遵循相同的模式 4444333322221111 所以我猜它们是一个整数 但我不太确定国际卡是什么样的 有0开头的吗 Up
  • 线程总是在增加

    我刚刚安装了 SmartFoxServer 重新启动 Sfs 后 Dashboard 线程池中的线程数不断增加 直到下次重新启动才再次减少 如果我增加线程池限制 线程数就会增加到该限制 任何扩展或服务尚未运行 线程数在 10 分钟内增加到
  • 验证有效的 SQL 字符串

    C 中是否有一种方法 或现有库 不一定内置于 NET 中 来执行简单的 SQL 字符串验证 场景 构建更新语句以减少 SQL 负载与单个语句的负载 如果字符串构建做了一些 奇怪 的事情 例如以逗号结尾 我希望能够验证该字符串是否正确 如果您
  • jQuery Validator,以编程方式显示错误

    我可以做这样的事情 validator showErrors nameOfField ErrorMessage 这工作得很好 但是如果我尝试做这样的事情 var propertyName nameOfField var errorMessa
  • 适用于 Visual Studio 2010 项目的 Mercurial .hgignore

    不要混淆适用于 Visual Studio 2008 项目的 Mercurial hgignore https stackoverflow com questions 34784 mercurial hgignore for visual
  • PHP/MySQL:突出显示“SOUNDS LIKE”查询结果

    快速 MYSQL PHP 问题 如果使用普通搜索查询找不到结果 我将使用 不太严格 的搜索查询作为后备 调整如下 foreach find array as word clauses firstname SOUNDS LIKE word O
  • 在 Express 中的 URL 中使用多个参数

    我将 Express 与 Node 一起使用 并且我有一个要求 用户可以请求 URL 如下所示 http myhost fruit apple red 此类请求将返回 JSON 响应 上述调用之前的 JSON 数据如下所示 fruit ap
  • ASP.NET 与 jQueryUI:服务器端事件未触发

    我有一个 ASP NET 页面 该页面使用 jQuery UI 对话框 当用户单击按钮时 btnGo 在页面中 我将检查用户是否登录 如果未登录 我将显示 jQuery UI 对话框进行登录 我使用了这段代码
  • Runtime.getRuntime().maxMemory()计算方法

    这是代码 System out println Runtime max mb Runtime getRuntime maxMemory MemoryMXBean m ManagementFactory getMemoryMXBean Sys
  • 与露天 cmis 的连接

    我正在尝试使用配置参数连接露天 但出现错误 Config sessionParameters put SessionParameter USER admin sessionParameters put SessionParameter PA
  • bash 进程替换中的 GNU 并行参数占位符

    我有以下 GNU 并行命令 parallel gnu jobs 4 normalize by median py k 20 C 20 paired N 4 x 6e9 out pdom diginorm fq pdom fq gz 200b
  • 如何在ie8中使用包含函数的值设置OnClick属性?

    我的目标是改变onclick链接的属性 我可以成功完成 但生成的链接在 ie8 中不起作用 它在 ff3 中确实有效 例如 这适用于 Firefox 3 但不适用于 IE8 为什么 p a href click me a p 您不需要为此使
  • 实现一个简单的文件下载 servlet [重复]

    这个问题在这里已经有答案了 我应该如何实现简单的文件下载servlet 这个想法是通过 GET 请求index jsp filename file txt 用户可以下载例如 file txt来自文件 servlet 文件 servlet 会
  • 这个 Monster Builder 是一个很好的 Builder / Factory 模式,用于抽象与 setter 混合的长构造函数吗?

    这是一个关于组合的人机界面问题步骤生成器模式 http rdafbn blogspot co uk 2012 07 step builder pattern 28 html与enhanced https stackoverflow com
  • 在记事本++中仅复制文本文件中的搜索表达式结果

    我有一个源代码 只想复制我用正则表达式找到的字符串 就像 asdladhsfhjk hello1 asdlkajhsd asdsa hello3 asdhjkl asd lkj hello5 我只是想从文本中复制 helloX 而且还不是线
  • Spring Security无状态配置

    我正在尝试按照文档实现 Spring 无状态身份验证 http static springsource org spring security site docs 3 1 x reference security filter chain
  • 使用“ODBC”将 Excel VBA 连接到 Oracle DB

    基本上我在一家软件公司工作 我的客户有一个 Oracle 数据库 我确实通过 SQL Developer 访问该数据库 我们也有一个虚拟桌面 里面有所有客户端应用程序 SQL Plus 等 现在 我团队中的另一个人创建了一个 Excel 宏
  • 使用 PHP 将文本分成两列

    我想知道是否可以将文本分成两部分 在我的网站上 我有一个产品描述 500 1000字 我想像这样显示它 div class text col div div class text col div 像这样的东西吗 len strlen inp
  • 编写一次并行数组 Haskell 表达式,通过 repa 和加速在 CPU 和 GPU 上运行

    修复并加速 API 相似度 Haskell repa 库用于在 CPU 上自动并行数组计算 加速库是 GPU 上的自动数据并行化 这些 API 非常相似 具有相同的 N 维数组表示 人们甚至可以在加速和修复阵列之间切换fromRepa an
  • Google Places API 自动完成仅获取城市列表

    我正在我的 Android 应用程序上实现谷歌的地点自动完成功能 它正在工作 显示每个相似的地点 但是只有当用户尝试搜索任何内容时 我如何才能获得城市建议 我搜索了很多 但找不到 Android 地点自动完成的类似问题 我已经从谷歌的示例中