简体   繁体   中英

How to dynamically set zoom value on Google Maps API during initialization

I have code like below.

<!DOCTYPE html>
<html>
  <head>
    <style type="text/css">
      html, body { height: 100%; margin: 0; padding: 0; }
      #map { height: 100%; }
    </style>
  </head>
  <body>
    <input type="hidden" id="zoom_data" value="8">
    <div id="map"></div>
    <script type="text/javascript">

var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: $('zoom_data').val()
  });
}

    </script>
    <script async defer
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>

But the maps goes blank. I just want to dynamically set zoom locally, not from server. Any advice?

Try the code below. You need to use document.getElementById() to get the value of the hidden field then convert it to number before using it as a zoom parameter.

<!DOCTYPE html>
<html>
  <head>
    <style type="text/css">
      html, body { height: 100%; margin: 0; padding: 0; }
      #map { height: 100%; }
    </style>
  </head>
  <body>
    <input type="hidden" id="zoom_data" value="8">
    <div id="map"></div>
    <script type="text/javascript">

var map;
 function initMap() {
    var zoom = document.getElementById('zoom_data').value;
    var nZoom = Number(zoom);
     map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: nZoom
  });
}

</script>
<script async defer
  src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM