Abdalla
Abdalla

Reputation: 2073

How to display a map on my wesbite and allow user to choose a country

Is there a known way where I can display a world map on my website and allow the user to choose a country to give him the appropriate content?

I know I can embed google maps, but for google maps, the user has unnecessary controls including zooming that I don't want to bother him with.

I would rather not use flash for this.

Thanks for advance.

Upvotes: 1

Views: 560

Answers (2)

Abdalla
Abdalla

Reputation: 2073

jqvmap seems to be perfect for the needs stated exactly.

Upvotes: 0

xomena
xomena

Reputation: 32138

You can create a select element with a list of countries. Each option should contain a two-letter ISO 3166-1 alpha-2 country code. When you select a country you can execute geocoding request for the country using components filtering. The response will return boundaries for the country, so you can fit Google maps to these boundaries.

Please find an example on jsbin: http://jsbin.com/qaxucex/edit?html,output

code snippet:

  var map;
  var geocoder;
  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: 0, lng: 0},
      zoom: 1
    });
    
    geocoder = new google.maps.Geocoder;
    
    var countryControlDiv = document.getElementById('countries');
    map.controls[google.maps.ControlPosition.TOP_CENTER].push(countryControlDiv);
  }
  
  function showCountry(code) {
    if (code === "") {
       map.setOptions({
          center: {lat: 0, lng: 0},
          zoom: 1
       });
    } else {
       geocoder.geocode({
          componentRestrictions: {
            country: code
          }
       }, function(results, status) {
          if (status === 'OK') {
            map.fitBounds(results[0].geometry.bounds);
          } else {
            window.alert('Geocode was not successful for the following reason: ' +
            status);
          }
        });
    }
  }
html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  #map {
    height: 100%;
  }
  #countries {
    margin-top: 12px;
  }
<div id="countries">
  <select id="country" onchange="showCountry(this.value);">
    <option value="">--Select country--</option>
    <option value="DE">Germany</option>
    <option value="ES">Spain</option>
    <option value="US">USA</option>
  </select>
</div>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&v=3&callback=initMap"></script>

Upvotes: 2

Related Questions