Search code examples
phpgoogle-mapslimitcountries

google maps: search in specific countries


I have a form in my PHP application which searches for locations in europe: Germany, France, Poland, Czech Republic, Spain, Austria, Romania, Italy.

This is my base query:

$address = "https://maps.googleapis.com/maps/api/geocode/json?address={$input}";

If the users tries to find "mannheim" for example, it should return Mannheim, Germany. Instead it returns a point in Pennsylvania, US. I tried adding this address component restriction: &components=administrative_area:EU, but this is not reliable because instead of finding Mannheim Germany, it points to a place 300 km away:

https://www.google.ro/maps/dir/50.5320001,6.6364339/Mannheim/@50.0388399,8.4546225,7.25z/data=!4m8!4m7!1m0!1m5!1m1!1s0x4797cc24518e3f45:0xb1e4fe7aa406e687!2m2!1d8.4660395!2d49.4874592?hl=en

If I append , Germany:

$address = "https://maps.googleapis.com/maps/api/geocode/json?address={$input}, Germany";

then the response is correct.

Is there a way to specify some countries for which the search should happen?

A last resort is to make a separate search for each country, but this would be really slow given the ~10-12 countries I search in.


Solution

  • Looks like it's possible now: https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-multiple-countries#maps_places_autocomplete_multiple_countries-javascript

      // Sets a listener on a given radio button. The radio buttons specify
      // the countries used to restrict the autocomplete search.
      function setupClickListener(id, countries) {
        const radioButton = document.getElementById(id);
        radioButton.addEventListener("click", () => {
          autocomplete.setComponentRestrictions({ country: countries });
        });
      }
      setupClickListener("changecountry-usa", "us");
      setupClickListener("changecountry-usa-and-uot", [
        "us",
        "pr",
        "vi",
        "gu",
        "mp",
      ]);