如何在我的网站上显示地图并允许用户选择一个国家

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

本文关键字:用户 选择 国家 一个 许用户 我的 网站 地图 显示      更新时间:2023-09-26

是否有一种已知的方式,我可以在我的网站上显示世界地图,并允许用户选择一个国家给他适当的内容?

我知道我可以嵌入谷歌地图,但对于谷歌地图,用户有不必要的控制,包括缩放,我不想打扰他。

我宁愿不使用flash。

可以创建一个包含国家列表的select元素。每个选项应包含两个字母的ISO 3166-1 alpha-2国家代码。当您选择一个国家时,您可以使用组件过滤执行该国家的地理编码请求。响应将返回该国家的边界,因此您可以将谷歌地图匹配到这些边界。

请在jsbin上查找示例:http://jsbin.com/qaxucex/edit?html,output

代码片段:

  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>

jqvmap似乎非常适合上述需求。