限制 Google 地点自动填充仅返回地址

问题描述 投票:0回答:3
autocomplete = new google.maps.places.Autocomplete(input, { types: ['geocode'] });

返回街道和城市以及其他较大区域。可以只限制在街道上吗?

google-places-api
3个回答
8
投票

这个问题很旧,但我想我会添加它以防其他人遇到这个问题。不幸的是,将类型限制为“地址”并没有达到预期的结果,因为仍然包含路由。因此,我决定做的是循环结果并执行以下检查:

result.predictions[i].types.includes('street_address')

不幸的是,我很惊讶地发现我自己的地址没有被包含在内,因为它返回以下类型:

{ types: ['geocode', 'premise'] }

因此,我决定启动一个计数器,任何在其类型中包含“地理代码”或“路线”的结果都必须至少包含一个其他术语(无论是“街道地址”还是“前提”或其他任何术语)。因此,路线被排除,任何具有完整地址的内容都将被包括在内。这并不万无一失,但效果相当好。

循环结果预测,并实现以下操作:

if (result.predictions[i].types.includes('street_address')) {
    // Results that include 'street_address' should be included
    suggestions.push(result.predictions[i])
} else {
    // Results that don't include 'street_address' will go through the check
    var typeCounter = 0;
    if (result.predictions[i].types.includes('geocode')) {
        typeCounter++;
    }
    if (result.predictions[i].types.includes('route')) {
        typeCounter++;
    }
    if (result.predictions[i].types.length > typeCounter) {
        suggestions.push(result.predictions[i])
    }
}

0
投票

我想你想要的是

{ types: ['address'] }

您可以通过此实时示例查看此操作:https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete(使用“地址”单选按钮)。


0
投票

看来我们可以通过将类型限制为

'street_address'
'premise'
来很好地解决这个问题(至少对于美国地址),并且除非输入的第一个字符是数字(0-9),否则不执行操作。

© www.soinside.com 2019 - 2024. All rights reserved.