-2

I'm using Google Place Autocomplete Data API to create my own autocomplete https://developers.google.com/maps/documentation/javascript/place-autocomplete-data. I've created a code based on documentation so it should return results only from Prague, Czech Republic. However when I try to enter data from another country it still displays results from this country. In this case it is expected to return zero results. The autocomplete should return only addresses so the user can choose it's own address

I've been using both approaches to limit zone to Prague, setting both in "old" and "new" way locationRestriction param

  // locationRestriction: {
        //     east: 50.177403,
        //     west: 14.7067945,
        //     north: 49.94193629,
        //     south: 14.2244533,
        // },
        locationRestriction: {
            "rectangle": {
                "low": {
                    "latitude": 49.94193629,
                    "longitude": 14.2244533
                },
                "high": {
                    "latitude": 50.177403,
                    "longitude": 14.7067945
                }
            }
        },

None of it actually limit the results to Prague. The coordinates should be ok, because I was using default google autocomplete before and they worked.

Full code with code to insert on html page

const loader = new Loader({
    apiKey: "",
    version: "weekly",
    libraries: ["places"],
});

async function initMap2() {
    let title;
    let results;
    let input;
    let token;
// Add an initial request body.
    let request = {
        input: "",
        locationRestriction: {
            "rectangle": {
                "low": {
                    "latitude": 49.94193629,
                    "longitude": 14.2244533
                },
                "high": {
                    "latitude": 50.177403,
                    "longitude": 14.7067945
                }
            }
        },
        strictBounds: true,
        region: 'cz',
        includedRegionCodes: ['cz'],
        includedPrimaryTypes: ["street_address", "street_number", "premise"],
        types: ['geocode', 'address'],
        componentRestrictions: {country: 'cz'}, // Restrict to Czech Republic
    };

    console.log(google.maps.places);
    token = new google.maps.places.AutocompleteSessionToken();
    title = document.getElementById("title");
    results = document.getElementById("results");
    input = document.querySelector("#billing_address_1");
    input.addEventListener("input", makeAcRequest);
    request = refreshToken(request);

    async function makeAcRequest(input) {
        // Reset elements and exit if an empty string is received.
        if (input.target.value == "") {
            title.innerText = "";
            results.replaceChildren();
            return;
        }

        // Add the latest char sequence to the request.
        request.input = input.target.value;

        // Fetch autocomplete suggestions and show them in a list.
        // @ts-ignore
        const {suggestions} =
            await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(
                request,
            );

        title.innerText = 'Query predictions for "' + request.input + '"';
        // Clear the list first.
        results.replaceChildren();

        for (const suggestion of suggestions) {
            const placePrediction = suggestion.placePrediction;
            // Create a link for the place, add an event handler to fetch the place.
            const a = document.createElement("a");

            a.addEventListener("click", () => {
                onPlaceSelected(placePrediction.toPlace());
            });
            a.innerText = placePrediction.text.toString();

            // Create a new list element.
            const li = document.createElement("li");

            li.appendChild(a);
            results.appendChild(li);
        }
    }

// Event handler for clicking on a suggested place.
    async function onPlaceSelected(place) {
        await place.fetchFields({
            fields: ["displayName", "formattedAddress"],
        });

        let placeText = document.createTextNode(
            place.displayName + ": " + place.formattedAddress,
        );

        results.replaceChildren(placeText);
        title.innerText = "Selected Place:";
        input.value = "";
        refreshToken(request);
    }

// Helper function to refresh the session token.
    async function refreshToken(request) {
        // Create a new session token and add it to the request.
        token = new google.maps.places.AutocompleteSessionToken();
        request.sessionToken = token;
        return request;
    }
}

loader.importLibrary('places').then(initMap2)
4
  • 1
    1) According to the documentation, locationRestriction must be a LatLngBounds or LatLngBoundsLiteral object. 2) There is no strictBounds parameter 3) There is no componentRestriction parameter - please refer to the documentation.
    – MrUpsidown
    Commented Jun 27 at 8:09
  • Am I right if I use this code to pass to locationRestriction const bounds = new google.maps.LatLngBounds(); bounds.extend(new google.maps.LatLng(49.94193629, 14.2244533)); // North-West corner bounds.extend(new google.maps.LatLng(50.177403, 14.7067945)); // South-East corner Commented Jun 27 at 9:08
  • 1
    You don't need to use the extend method. You can construct it right away. See developers.google.com/maps/documentation/javascript/reference/….
    – MrUpsidown
    Commented Jun 27 at 9:47
  • 1
    Btw. you linked to the docs in your question, which has a complete and working example at the end...
    – MrUpsidown
    Commented Jun 27 at 12:35

0