Change zoom with html tag event

前端 未结 3 1191
慢半拍i
慢半拍i 2021-01-16 22:48

i\'am a beginner in GMaps API and javascript, so this should be an easy question for you that are really experts. I have started to \"play around\" with the API, and wanted

相关标签:
3条回答
  • 2021-01-16 22:57

    map is a local variable to initialise() - the other functions don't have access to it, so declare it outside of initialise(). Then have a new function that returns the map's current zoom.

    var map;
    
    function initialize() {
      var mapOptions = {
        center: new google.maps.LatLng(-35.8190,-61.9010),
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.SATELLITE
      };
      map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    }
    
    function getCurentZoom() {
      return map.getZoom();
    }
    
    function cambiarZOOM(nro) {
      var newZ = getCurentZoom() + nro;
      map.setZoom(newZ);
    }    
    
    google.maps.event.addDomListener(window, 'load', initialize);
    
    0 讨论(0)
  • 2021-01-16 22:59

    Your problem is that the cambiarZOOM function and map variable are only accessible within the scope of the initialize function. To use a function on an onclick event, either it has to be available globally (this is discouraged), or you have to attach the function to the button while the function is in scope.

    If you give your button an id (id='zoomButton'), you can attach cambiarZOOM within the initialize function like so:

    ...
    function cambiarZOOM(nro) {
        var newZ = ez + nro;
        map.setZoom(newZ);
        }
    }
    
    var button = document.getElementById('zoomButton');
    button.onclick = function () { cambiarZOOM(5); };
    
    0 讨论(0)
  • 2021-01-16 23:15

    Your cambiarZOOM function is local to the initialize function (it is contained by that function). It needs to be in the global scope (outside of any function declaration) to be used in an HTML event handler (like "onclick"). Your "map" variable also needs to be global to be used in it.

    <script type="text/javascript">
    var map = null;
    function initialize() {
    
        //CREATE THE MAP
        var mapOptions = {
          center: new google.maps.LatLng(-35.8190,-61.9010),
          zoom: 15,
          mapTypeId: google.maps.MapTypeId.SATELLITE
        };
        map = new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);
    }
    google.maps.event.addDomListener(window, 'load', initialize);
    
    function cambiarZOOM(nro) {
        //GET THE ZOOM
        var ez = map.getZoom();
        var newZ = ez + nro;
        map.setZoom(newZ);
        }
    
    </script>
    
    0 讨论(0)
提交回复
热议问题