基于Google Map API实现土耳其3个指定行政区的搜索过滤咨询
Great question! The issue with checking fixed indices (like address_components[0] or [1]) is that the structure of these components varies widely depending on the place type—sometimes the district might show up early in the list, other times it’s buried deeper. Let’s fix this with a robust, dynamic approach:
Step 1: Define Allowed Districts
First, create a set of your target districts for fast, efficient lookups:
const allowedDistricts = new Set(['Sarıyer', 'Beşiktaş', 'Şişli']);
Step 2: Dynamically Find the District Component
Instead of hardcoding indices, loop through all address components to find the one labeled as administrative_area_level_2 (this is the standard type for Turkish districts):
// Attach this to your autocomplete's place_changed event autocomplete.addListener('place_changed', () => { const place = autocomplete.getPlace(); // Guard clause: Ensure place has address data if (!place.address_components || place.address_components.length === 0) { alert('You can only search in these 3 districts'); autocomplete.set('value', ''); // Clear invalid input return; } // Find the district (administrative_area_level_2) in components let userDistrict = null; for (const component of place.address_components) { if (component.types.includes('administrative_area_level_2')) { userDistrict = component.long_name; break; } } // Validate the district if (!userDistrict || !allowedDistricts.has(userDistrict)) { alert('You can only search in these 3 districts'); autocomplete.set('value', ''); // Reset input return; } // If valid: Add marker to map and center view const location = place.geometry.location; new google.maps.Marker({ position: location, map: map, title: place.name }); map.setCenter(location); map.setZoom(12); // Adjust zoom level as needed });
Step 3: Optional (But Recommended) Bias Results to Your Area
To guide users toward valid results, add bounds to your autocomplete to prioritize locations in the target districts:
// Define rough bounds covering Sarıyer, Beşiktaş, Şişli (adjust coordinates if needed) const targetBounds = new google.maps.LatLngBounds( new google.maps.LatLng(41.01, 29.00), // Southwest corner new google.maps.LatLng(41.18, 29.15) // Northeast corner ); // Initialize autocomplete with bounds bias const autocomplete = new google.maps.places.Autocomplete( document.getElementById('your-search-input-id'), { bounds: targetBounds, strictBounds: false, // Set to true only if you want to block results outside bounds entirely types: ['geocode'] // Optional: Restrict results to geographic locations } );
Why This Works
- By targeting
administrative_area_level_2, we reliably pull the district regardless of where it appears in the address component list. - Using a
Setfor allowed districts ensures fast, O(1) lookups. - Guard clauses handle edge cases where a place might not have district data.
Content of the question originates from Stack Exchange, question author Leon Rio

