【问题标题】:Changing zoom level of google map with user input使用用户输入更改谷歌地图的缩放级别
【发布时间】:2019-03-16 08:41:06
【问题描述】:

我正在尝试根据用户输入更改我的谷歌地图的缩放级别。

<script type="text/javascript">

    var map;

    function initMap() {    
    var uluru = {lat: 37.7749, lng: -122.4194};    
    var map = new google.maps.Map(document.getElementById('map'), {    
    zoom: 10,    

       // standard google map javascript

    } //end of initMap() 


    $('#id_zoomlevel').on('change', function() {
       var zoomlevel = $('#id_zoomlevel :selected').attr('value');
       map.setZoom(zoomlevel);
    });

</script>

我收到以下错误:

(index):679 Uncaught TypeError: Cannot read property 'setZoom' of undefined

如何将现在设置的 map 变量传递给“on change”函数?

【问题讨论】:

    标签: javascript jquery google-maps


    【解决方案1】:

    您的问题是 map 既是您的 initMap 方法的局部变量,又是全局变量。当您在initMap 方法中执行var map 时,您将创建一个属于您的initMap 方法的新map 变量,而不是更改外部全局变量map。因此,它类似于:

    var b;
    function a() {
      var b = "foo"; // creates a new `b` variable within `a` (and thus nott modifying the outer `b` variable)
    }
    a();
    console.log(b); // cannot access `b` outside of `a` (similar to `initMap`)

    但如果您从内部方法中删除 var,您将改为更改全局变量(而不是创建新的局部变量):

    var b;
    function a() {
      b = "foo";
    }
    a();
    console.log(b); // cannot access `b` outside of `a` (similar to `initMap`)

    因此,您的代码应该是这样的:

    <script type="text/javascript">
    
        var map; // declare as global
    
        function initMap() {    
        var uluru = {lat: 37.7749, lng: -122.4194}; 
        //\/ --- initialize the global `map` variable (don't create a new local map variable)   
        map = new google.maps.Map(document.getElementById('map'), {    
        zoom: 10,    
    
           // standard google map javascript
    
        } //end of initMap() 
    
    
        $('#id_zoomlevel').on('change', function() {
           var zoomlevel = $('#id\_zoomlevel :selected').attr('value');
           map.setZoom(zoomlevel);
        });
    
    </script>
    

    【讨论】:

      【解决方案2】:

      您在initMap() 函数中声明了新的map 变量

      <script type="text/javascript">
      
          var map;
      
          function initMap() {    
          var uluru = {lat: 37.7749, lng: -122.4194};    
          map = new google.maps.Map(document.getElementById('map'), {    
          zoom: 10,    
          . . . . . . standard google map javascript .....
      
      
          $('#id_zoomlevel').on('change', function() {
             var zoomlevel = $('#id\_zoomlevel :selected').attr('value');
             map.setZoom(zoomlevel);
          });
      
      </script>
      

      使用全局映射变量而不是本地变量

      【讨论】:

        猜你喜欢
        • 2012-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多