Как ограничить автозаполнение Google maps только одной страной?

Я перепробовал все, чтобы мой поисковый запрос выдавал только варианты автозаполнения только из Доминиканской Республики, но я не смог этого добиться, кто-нибудь здесь знает, как это сделать?


<input 
                                    type="text" 
                                    id="searchInput" 
                                    class="form-control" 
                                    placeholder="Search for a location..."
                                >

let autocomplete;

const input = document.getElementById('searchInput');
    autocomplete = new google.maps.places.Autocomplete(input, {
        types: ['(cities)', 'geocode'], // Allow both city and address searches
        componentRestrictions: { country: 'do' }
    });

    // Handle place selection
    autocomplete.addListener('place_changed', function() {
        const place = autocomplete.getPlace();
        
        if (!place.geometry) {
            return;
        }

Вы можете использовать этот метод; он предлагает только страны в Доминиканской Республике и хорошо работает.

Если вы используете javascript, то ниже приведен код для этого

import React, { useEffect, useRef } from 'react';

export function App() {
  const inputRef = useRef(null);
  const autocompleteRef = useRef(null);

  useEffect(() => {
    if (window.google) {
      // Initialize the Google Maps Places Autocomplete
      autocompleteRef.current = new window.google.maps.places.Autocomplete(
        inputRef.current,
        {
          types: ['(cities)'], // Only restrict to cities
          componentRestrictions: { country: 'do' }, // Limit to Dominican Republic
        }
      );

      // Handle the place selection
      autocompleteRef.current.addListener('place_changed', () => {
        const place = autocompleteRef.current.getPlace();
        if (place.geometry) {
          console.log('Selected place:', place);
          // You can handle the selected place here
        } else {
          console.log('No place found.');
        }
      });
    }
  }, []);

  return (
    <div className='App'>
      <h1>Google Maps Autocomplete</h1>
      <input
        ref={inputRef}
        type='text'
        className='form-control'
        placeholder='Search for a location in Dominican Republic...'
      />
    </div>
  );
}

 
деленья деленья

и если вы хотите использовать html, то это прекрасно работает.

Вам просто нужно добавить СВОЙ_GOOGLE_MAPS_API_KEY

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Google Maps Autocomplete</title>
  <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY&libraries=places&callback=initAutocomplete" async defer></script>
  <style>
    .container {
      max-width: 400px;
      margin: 0 auto;
      padding-top: 50px;
    }
    input {
      width: 100%;
      padding: 8px;
      font-size: 16px;
    }
  </style>
</head>
<body>

  <div class="container">
    <h1>Google Maps Autocomplete</h1>
    <input id="autocomplete" type="text" class="form-control" placeholder="Search for a location in Dominican Republic...">
  </div>

  <script>
    let autocomplete;

    // Initialize the Google Maps Places Autocomplete
    function initAutocomplete() {
      const input = document.getElementById('autocomplete');
      
      autocomplete = new google.maps.places.Autocomplete(input, {
        types: ['(cities)'],  // Only restrict to cities
        componentRestrictions: { country: 'do' },  // Limit to Dominican Republic
      });

      // Handle the place selection
      autocomplete.addListener('place_changed', function() {
        const place = autocomplete.getPlace();
        if (place.geometry) {
          console.log('Selected place:', place);
          // Handle the selected place here
        } else {
          console.log('No place found.');
        }
      });
    }
  </script>

</body>
</html>
деленья деленья

Вернуться на верх