【问题标题】:How to display a map on my wesbite and allow user to choose a country如何在我的网站上显示地图并允许用户选择国家
【发布时间】:2023-03-13 05:39:01
【问题描述】:

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

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

我宁愿不为此使用闪光灯。

感谢您的提前。

【问题讨论】:

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


【解决方案1】:

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

请在jsbin上找一个例子:http://jsbin.com/qaxucex/edit?html,output

代码 sn-p:

  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>

【讨论】:

  • 据我了解,OP 希望用户使用地图而不是列表/下拉列表来选择国家/地区。
【解决方案2】:

jqvmap 似乎非常适合确切说明的需求。

【讨论】:

    猜你喜欢
    • 2011-03-09
    • 1970-01-01
    • 2013-11-27
    • 2021-07-08
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多