Search code examples
javascriptreactjsgeocodinggoogle-geocoder

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


so I'm using the built in geocoder.geocode function for google maps and implementing it like so:

   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')
        }
    })

this all works fine. however, during some testing I noticed a bug. I searched for Split in Croatia but it added Split in California to my map. This got me thinking if there is a way for it to return a list of results for all Splits in this case, so the user can then select the chosen one and then I add it to the map. is it possible for this function to cater to that? or is there more logic I need to add?


Solution

  • You'll notice that this code:

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

    ...returns a results array, and you're accessing results[0].

    According to the 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.

    So, you may want to prompt the user if the results array contains more than one value.

    EDIT: Since you've replied that you're only getting one value in the results array, you may want to check out this Google blog post about address geocoding, which states:

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

    You may want to use their 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.