You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Places组件限制失效:无法将搜索范围限定在美国

问题原因与解决方案

你代码里的componentRestrictions配置位置错误,新的PlaceAutocompleteElement需要将该配置嵌套在options对象中才能生效。

修正后的代码如下:

"use strict";
/*
 * @license
 * Copyright 2025 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

async function initMap() {
    
    // Request needed libraries.
    await google.maps.importLibrary("places");
    // Create the input HTML element, and append it.
    //@ts-ignore
    const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement({
        options: {
            componentRestrictions: { country: ['us'] }
        }
    });
    //@ts-ignore
    document.body.appendChild(placeAutocomplete);
    
    // Inject HTML UI.
    const selectedPlaceTitle = document.createElement('p');
    selectedPlaceTitle.textContent = '';
    document.body.appendChild(selectedPlaceTitle);
    const selectedPlaceInfo = document.createElement('pre');
    selectedPlaceInfo.textContent = '';
    document.body.appendChild(selectedPlaceInfo);
    
    // Add the gmp-placeselect listener, and display the results.
    //@ts-ignore
    placeAutocomplete.addEventListener('gmp-select', async ({ placePrediction }) => {
        const place = placePrediction.toPlace();
        await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] });
        selectedPlaceTitle.textContent = 'Selected Place:';
        selectedPlaceInfo.textContent = JSON.stringify(place.toJSON(), /* replacer */ null, /* space */ 2);
    });
    
}
initMap();

核心修改点:将componentRestrictions包裹在options对象内,这是新的PlaceAutocompleteElement构造参数的要求,只有这样组件才能正确识别并应用地域限制规则。

内容的提问来源于stack exchange,提问作者AlejoDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 09:58:23