Google 在 Stenciljs 中解决自动完成 api

Google address autocomplete api in Stenciljs

我正在尝试在 Stenciljs 组件中使用 google 的地址自动完成功能为地址添加搜索字段。上面没有任何资源。

首先您需要加载 google 地图 api 脚本,以便您可以与全局 google.maps 对象进行交互。您可以通过包含脚本标记来实现,也可以编写类似以下辅助函数的内容。

const googleApiKey = '...';

export const importMapsApi = async () =>
    new Promise<typeof google.maps>((resolve, reject) => {
        if ('google' in window) {
            return resolve(google.maps);
        }

        const script = document.createElement('script');

        script.onload = () => resolve(google.maps);
        script.onerror = reject;
        script.src = `https://maps.googleapis.com/maps/api/js?key=${googleApiKey}&libraries=places`;

        document.body.appendChild(script);
    });

为了获取全局 google 对象的 TypeScript 类型,您应该将 @types/googlemaps 安装到您的开发依赖项中。

然后您需要实现一个允许您搜索地点的功能,例如。 g.:

export const searchForPlaces = async (input: string, sessionToken: google.maps.places.AutocompleteSessionToken) => {
    const maps = await importMapsApi();

    const service = new maps.places.AutocompleteService();

    return new Promise<google.maps.places.AutocompletePrediction[]>((resolve) =>
        service.getPlacePredictions({ input, sessionToken }, (predictions, status) => {
            if (status !== maps.places.PlacesServiceStatus.OK) {
                return resolve([]);
            }

            resolve(predictions);
        }),
    );
};

None 其中特定于 Stencil 顺便说一句。剩下要做的就是在组件中使用 searchForPlaces 函数。一个非常简单的例子是这样的:

@Component({ tag: 'maps-place-search' })
export class MapsPlaceSearch {
    sessionToken: string;

    @State()
    predictions: google.maps.places.AutocompletePrediction[];

    async componentWillLoad() {
        const maps = await importMapsApi();
        this.sessionToken = new maps.places.AutoCompleteSessionToken();
    }

    async search = (e: InputEvent) => {
        const searchTerm = e.target.value;

        if (!searchTerm) {
            this.predictions = [];
            return;
        }

        this.predictions = await searchForPlaces(searchTerm, this.sessionToken);
    }

    render() {
        return (
            <Fragment>
                <input onInput={this.search} />
                <ul>
                    {this.predictions.map(prediction => <li key={prediction.description}>{prediction.description}</li>)}
                </ul>
            <Fragment>
        );
    }
}

地点搜索将为您提供每个预测的 placeId。您可以将那个和会话令牌传递给 maps.places.PlacesService 以获取该地点的详细信息并自动填写您的表格或您想要实现的任何目标。