如何使用地理编码器 API 从 Google 查询结果列表?

How to query for a list of results using geocoder API from Google?

所以我为 google 地图使用内置的 geocoder.geocode 函数并像这样实现它:

   geocoder.geocode({ address: place }, function (results, status) {
        if (status == window.google.maps.GeocoderStatus.OK) {
            const cityLat = results[0].geometry.location.lat()
            const cityLng = results[0].geometry.location.lng()
            setMapMarkers([...mapMarkers, cityInformation])
            // other logic here that loads it on to the map
        } else {
            alert('Place not recognized, please try searching again')
        }
    })

一切正常。然而,在一些测试中,我发现了一个错误。我在克罗地亚搜索 Split,但它在我的地图中添加了加利福尼亚的 Split。这让我开始思考,在这种情况下,是否有办法 return 所有 Split 的结果列表,这样用户就可以 select 选择一个,然后我添加它到地图。这个功能有可能迎合那个吗?还是我需要添加更多逻辑?

您会注意到这段代码:

geocoder.geocode({ address: place }, function (results, status) {

...returns 一个 results 数组,并且您正在访问 results[0].

根据 Google Maps developer Guide,

Generally, only one entry in the "results" array is returned for address lookups, though the geocoder may return several results when address queries are ambiguous.

因此,如果 results 数组包含多个值,您可能希望提示用户。

编辑:既然您已经回答说您在 results 数组中只得到一个值,您可能想查看这个 Google blog post about address geocoding,其中指出:

The Geocoding API is best for handling unambiguous queries: complete postal address strings (for example, “48 Pirrama Rd, Pyrmont, NSW, Australia”).

您可能想使用他们的 Places API:

For applications that respond in real time to user input, we recommend using the Place Autocomplete service in the Places API. This service is designed to return multiple possible addresses and allow the user to choose between them.