如何通过Google Maps API从Places中获取一致的城市、州(地区)与国家值?
稳定提取Google Place对象地址字段的通用方案
核心逻辑
业界通用的标准方案为按address_components的types字段匹配目标值,完全不依赖数组固定索引,兼容不同国家、不同城市的地址结构差异。
匹配规则对应关系:
- 城市(City):匹配
types数组中包含locality的组件,优先取long_name值 - 地区/州/省(State):匹配
types数组中包含administrative_area_level_1的组件,可按需选择long_name(全称)或short_name(短代码,如QLD、AU) - 国家(Country):匹配
types数组中包含country的组件,可按需取long_name(国名全称)或short_name(ISO国家代码)
实现代码
不需要编写复杂的嵌套循环,直接通过遍历匹配类型即可:
/** * 从地址组件数组中提取目标类型的值 * @param {Array} components - place.address_components 返回的数组 * @param {string} targetType - 要匹配的地址类型 * @param {boolean} useShortName - 是否返回短名称,默认返回全称 * @returns {string} 匹配到的值,未匹配到返回空字符串 */ function getAddressValue(components, targetType, useShortName = false) { const matched = components.find(item => item.types.includes(targetType)); return matched ? (useShortName ? matched.short_name : matched.long_name) : ''; }
替换原有取值逻辑的调用示例:
autocomplete.addListener("place_changed", () => { const place = autocomplete.getPlace(); // 完全不需要关注address_components的索引顺序 const city = getAddressValue(place.address_components, 'locality'); const stateCode = getAddressValue(place.address_components, 'administrative_area_level_1', true); const countryCode = getAddressValue(place.address_components, 'country', true); console.log('提取结果:', { city, stateCode, countryCode }); });
注意事项
- 匹配逻辑仅判断目标类型是否存在,不需要过滤
political这类重复的冗余类型,只要目标类型存在即可命中,可靠性不受冗余字段影响 - 已将Autocomplete的结果类型限制为
['(cities)']的场景下,返回的结果必然包含上述三类核心地址字段,不会出现匹配为空的情况 - 遇到少数无
locality字段的特殊建制区域,可增加一层兜底:当locality匹配为空时,再尝试匹配administrative_area_level_2作为城市值,可覆盖绝大多数全球区域的地址结构
内容的提问来源于stack exchange,提问作者user1063287
相关产品推荐
相关产品推荐

