Trollwut
Trollwut

Reputation: 551

How to center on a map by zip code for a specific country?

I'm using Google Maps API v3 to handle a map. In addition I took an input/text and an input/button to let the user look for a zip code.

The map then should center on that zipcode. And it does! But on some zip codes I come to very exotic places.

The server, client and anything else is in Germany, so I would like to lock all queries to Germany. For example if I want to center on "92224" I don't see Bavaria, I get lost in Lithuania.

I'm using the following code from this answer to center by command:

function codeAddress(zipCode) {
    geocoder.geocode( { 'address': zipCode}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        //Got result, center the map and put it out there
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

Now how can I achieve that this query only will center on German zip codes? (If it helps, German zip codes are always 5 numbers long.)

Upvotes: 2

Views: 2847

Answers (1)

MrUpsidown
MrUpsidown

Reputation: 22497

You want to setup componentRestrictions and filter by country.

See the documentation.

Example:

function codeAddress(zipCode) {

    geocoder.geocode({
        'address': address, "componentRestrictions":{"country":"DE"}
    }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {

            map.setCenter(results[0].geometry.location);

            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });

        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

Demo:

JSFiddle demo

Note:

As a side note, you cannot filter by multiple countries. This is a long awaited feature that Google still didn't implement until now.

Edit: 2017-04-19

Google has now implemented a way to filter by up to 5 countries: see https://issuetracker.google.com/issues/35821685 I will not make any comment about how much useful this is...

Upvotes: 1

Related Questions