Google Maps getPlacePredictions的radius属性失效问题及解决咨询
Let me break down the issue first: the radius parameter in getPlacePredictions isn't a strict filter—it's just a search preference. Google Places API will prioritize results within your specified 50km zone around Moscow, but if there aren't enough matching results for your input (like "Sara") in that area, it'll expand the search to find relevant entries elsewhere. That's why you're seeing Saransk, which is 650km away, pop up.
Fix: Enable Strict Boundary Enforcement
To force the API to only return results within your defined radius, you need to add the strictBounds: true parameter to your request. This flag tells the API to strictly respect the location and radius you've set, and never return results outside that area.
Here's your updated code (I also added a line to clear old results to avoid duplicate entries on each keystroke):
const autoComplete = new google.maps.places.AutocompleteService(); const input = document.querySelector('#search'); const result = document.querySelector('#result'); const getPlaceAutocomplete = (value) => { autoComplete.getPlacePredictions({ input: value, location: new google.maps.LatLng(55.755826, 37.617300), // Moscow coordinates radius: 50000, // 50km radius strictBounds: true, // Enforce strict radius limits componentRestrictions: { country: 'ru' }, }, (data) => { result.innerHTML = ''; // Clear previous results first if (data) { data.forEach((item) => { result.innerHTML += `<li>${item.description}</li>`; }); } }); }; input.addEventListener('keyup', () => { const value = input.value.trim(); getPlaceAutocomplete(value); });
Extra Notes
- The
strictBoundsflag works with bothlocation+radiusand theboundsparameter (if you want to define a custom rectangular area instead of a circle). - If you search for a term that has no matches within the 50km radius, the API will return an empty response—this is expected behavior since we're enforcing strict limits.
- I added
trim()to the input value to avoid unnecessary requests triggered by empty whitespace.
内容的提问来源于stack exchange,提问作者Aleksandr Gvozdev

