javascript - 如何在我的网站上显示 map 并允许用户选择国家

标签 javascript html google-maps google-maps-api-3

有没有一种已知的方法可以在我的网站上显示世界地图并允许用户选择一个国家来为其提供适当的内容?

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

我宁愿不为此使用 flash。

感谢提前。

最佳答案

您可以创建一个带有国家列表的选择元素。每个选项都应包含两个字母的 ISO 3166-1 alpha-2 国家/地区代码。当您选择一个国家时,您可以使用组件过滤对该国家执行地理编码请求。响应将返回国家/地区的边界,因此您可以使 Google map 适应这些边界。

请在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>

关于javascript - 如何在我的网站上显示 map 并允许用户选择国家,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39318847/

相关文章:

javascript - 过滤器黑名单

javascript - 如何将 bool 值从 javascript 传递给 python?

javascript - 如何在 Javascript 中创建一个对象作为默认值的多维数组?

java - 如何将两个 8 位十进制数转换为字母或字母数字代码

javascript - 如果元素有类

javascript - 如何使用 &lt;input type ="number"> 更改线宽?

html - 使用 Bootstrap 的流体网格系统

HTML 5 视频标签范围标题

Android Google Maps Api V2 崩溃

android - Android 2.2 中的 GOOGlE API V2 问题