首页 > 解决方案 > 如何在我的场景中使某些变量成为全局变量?

问题描述

我正在使用 Google Maps JavaScript API 和 HTML 表单根据用户在表单中输入的纬度和经度坐标将标记添加到地图上。以下是我的 HTML 页面中的正文代码:

<body>
    <div id="mainForm">
        <form id="mainForm" name="mainForm" method="get">

        Latitude: <input type="text" id="latitude" name="latitude">
        Longitude: <input type="text" id="longitude" name="longitude">
        <input type="submit" name="submit" onClick="results(this.form)">

        </form>
    </div>

    <!--The div element for the map -->
    <div id="map">
    <script>
        var latitudeNew;
        var longitudeNew;
        function results (form) {
            latitudeNew = parseFloat(form.latitude.value);
            longitudeNew = parseFloat(form.longitude.value);
            console.log(latitudeNew);
        }
// Initialize and add the map
function initMap() {
  // The location of the markers
  var UScenter = {lat: 38.1, lng: -96.8};
  var formInput = {lat: latitudeNew, lng: longitudeNew};
  // The map, centered on the U.S.
  var map = new google.maps.Map(
      document.getElementById('map'), {
          zoom: 5,
          center: UScenter,
          disableDefaultUI: true,
          zoomControl: true
      });
  map.setOptions({ minZoom: 3, maxZoom: 20 });

  var contentString = '<div id="content">'+
      '<div id="siteNotice">'+
      '</div>'+
      '<h1 id="firstHeading" class="firstHeading">Hello</h1>'+
      '<div id="bodyContent">'+
      '<p>Name</p>'+
      '</div>'+
      '</div>';

  var infowindow = new google.maps.InfoWindow({
    content: contentString
  });

  // The markers
  var marker = new google.maps.Marker({position: formInput, map: map});
  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });
}
    </script>

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

通过查看代码您可能已经知道,我的表单results在提交时调用了函数,该函数定义了变量latitudeNewlongitudeNew. 这些变量稍后在函数中使用变量initMap来定义标记的位置formInput。我知道这个问题与我正在创建的单独的全局变量和局部变量有关,但是我试图解决这个问题的各种解决方案对我不起作用,例如将变量定义为window.latitude/longitude和定义外部变量的功能。

所以我的具体问题是如何定义latitudeNewlongitudeNew变量以及将它们放置在哪里,以便我可以将用户在表单中插入的输入值正确地传递到谷歌地图上的标记?

标签: javascriptgoogle-mapsvariablesscopeglobal-variables

解决方案


两件事情:

  1. 地图被初始化,initMap当前是 API 的回调(因此它在 API 完成加载时运行,然后用户可以单击按钮)。&callback=initMap从 API 中移除的包括:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY">

  1. 表单post正在重新加载页面,破坏地图,添加return false;<input type="submit">标签中的onclick函数:
<input type="submit" name="submit" onClick="results(this.form); return false;">

工作代码片段:*

html,
body,
#map {
  height: 100%;
  width" 100%;
 margin: 0;
  padding: 0;
}
<div id="mainForm">
  <form id="mainForm" name="mainForm" method="get">

    Latitude: <input type="text" id="latitude" name="latitude" value="38.1"> Longitude: <input type="text" id="longitude" name="longitude" value="-96.8">
    <input type="submit" name="submit" onClick="results(this.form); return false;">

  </form>
</div>

<!--The div element for the map -->
<div id="map">
  <script>
    var latitudeNew;
    var longitudeNew;

    function results(form) {
      latitudeNew = parseFloat(form.latitude.value);
      longitudeNew = parseFloat(form.longitude.value);
      console.log(latitudeNew);
      initMap();
    }
    // Initialize and add the map
    function initMap() {
      // The location of the markers
      var UScenter = {
        lat: 38.1,
        lng: -96.8
      };
      var formInput = {
        lat: latitudeNew,
        lng: longitudeNew
      };
      var college = "<?php echo $college ?>;"
      // The map, centered on the U.S.
      var map = new google.maps.Map(
        document.getElementById('map'), {
          zoom: 5,
          center: UScenter,
          disableDefaultUI: true,
          zoomControl: true
        });
      map.setOptions({
        minZoom: 3,
        maxZoom: 20
      });

      var contentString = '<div id="content">' +
        '<div id="siteNotice">' +
        '</div>' +
        '<h1 id="firstHeading" class="firstHeading">University of California, San Diego</h1>' +
        '<div id="bodyContent">' +
        '<p>Devin Provence</p>' +
        '</div>' +
        '</div>';

      var infowindow = new google.maps.InfoWindow({
        content: contentString
      });

      // The markers
      var marker = new google.maps.Marker({
        position: formInput,
        map: map
      });
      marker.addListener('click', function() {
        infowindow.open(map, marker);
      });
    }
  </script>

  <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk">
  </script>
</div>


推荐阅读