在页面加载时触发两个JavaScript函数的问题

时间:2018-07-17 13:49:17

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

页面加载时,我需要启动两个javascript函数。

用于初始化Google地图的功能:

function initialize() {
    var myLatLng = new google.maps.LatLng(52.015460,18.498087);
        var myOptions = {
            zoom: 6,
            center: myLatLng,
            mapTypeId: 'hybrid',
            clickableIcons: false 
    };
    }

在地图初始化和页面加载时自动聚焦于输入字段的功能:

function inputfocus() {
    document.getElementById("pac-input").focus();
}

要启动上述功能,我正在使用以下代码:

function start() {
    initialize();
    inputfocus();
}
window.onload = start;

我面临的问题是,这些函数可以单独正常工作,但按上述顺序,只有第一个触发(即仅加载地图)。

我已经阅读并测试了stackoverflow和其他网站上提供的许多想法,但没有一个起作用。

如果您对解决此问题有任何想法,请告诉我。

一个演示示例如下(需要添加Google Maps自己的密钥):

    <!DOCTYPE html>
<html>
  <head>
    <title>test</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">

    <style>
      #mapindex {
        height: 400px;  
        width: 100%;
       }
    </style>

    <script src="https://maps.googleapis.com/maps/api/js?key=yourapikeygoeshere&libraries=places&types=(cities)" ></script>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <!-- Google Maps API -->    

    <script>

        function initialize() {
            var myLatLng = new google.maps.LatLng(52.015460,18.498087); // Map is centered here  
            var myOptions = {
                zoom: 6,
                center: myLatLng,
                mapTypeId: 'hybrid',
                clickableIcons: false
        };

        map = new google.maps.Map(document.getElementById("mapindex"), myOptions);


        // Create the search box and link it to the UI element.

        var input = document.getElementById('pac-input');

        var searchBox = new google.maps.places.SearchBox(input);
        map.controls[google.maps.ControlPosition.TOP_CENTER].push(input);

        // Bias the SearchBox results towards current map's viewport.
        map.addListener('bounds_changed', function() {
        searchBox.setBounds(map.getBounds());
        });

        var markers = [];
        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener('places_changed', function() {
        var places = searchBox.getPlaces();

        if (places.length == 0) {
          return;
        }

        // Clear out the old markers.
        markers.forEach(function(marker) {
          marker.setMap(null);
        });
        markers = [];

        // For each place, get the icon, name and location.
        var bounds = new google.maps.LatLngBounds();
        places.forEach(function(place) {
          if (!place.geometry) {
            console.log("Returned place contains no geometry");
            return;
          }
          var icon = {
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(25, 25)
          };

           // Create a marker for each place.
            var image = 'http://www.instead.com.pl/target2.png';
              markers.push(new google.maps.Marker({
                map: map,
                icon: image,
                title: place.name,
                position: place.geometry.location
              }));

          if (place.geometry.viewport) {
            // Only geocodes have viewport.
            bounds.union(place.geometry.viewport);
          } else {
            bounds.extend(place.geometry.location);
          }
        });
        map.fitBounds(bounds);
        });


        }

    </script>

    <script>

        function inputFocus() {
            document.getElementById("pac-input").focus();
        }

    </script>

    <script>
        function start() {
          initialize();
          inputFocus();
        }
        window.onload = start;
    </script>

  </head>
  <body>

    <input id="pac-input" class="controls" type="text" placeholder="Enter location" value="<?php if(isset ($_GET['local'])){ echo $_GET['local'];}?>"/>
    <div id="mapindex"></div>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

如果我在setFocus上添加延迟(如Sergii Vorobei在评论中所建议),那么它会起作用。

google.maps.event.addListenerOnce(map, 'idle', function(){
  setTimeout(inputFocus, 1000);
});

(您可能不需要“空闲”事件侦听器,但可能更安全)

proof of concept fiddle

代码段:

#mapindex {
  height: 400px;
  width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&types=(cities)"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Google Maps API -->

<script>
  function initialize() {
    var myLatLng = new google.maps.LatLng(52.015460, 18.498087); // Map is centered here  
    var myOptions = {
      zoom: 6,
      center: myLatLng,
      mapTypeId: 'hybrid',
      clickableIcons: false
    };

    function inputFocus() {
      document.getElementById("pac-input").focus();
    }

    map = new google.maps.Map(document.getElementById("mapindex"), myOptions);


    // Create the search box and link it to the UI element.

    var input = document.getElementById('pac-input');

    var searchBox = new google.maps.places.SearchBox(input);
    map.controls[google.maps.ControlPosition.TOP_CENTER].push(input);

    // Bias the SearchBox results towards current map's viewport.
    map.addListener('bounds_changed', function() {
      searchBox.setBounds(map.getBounds());
    });

    var markers = [];
    // Listen for the event fired when the user selects a prediction and retrieve
    // more details for that place.
    searchBox.addListener('places_changed', function() {
      var places = searchBox.getPlaces();

      if (places.length == 0) {
        return;
      }

      // Clear out the old markers.
      markers.forEach(function(marker) {
        marker.setMap(null);
      });
      markers = [];

      // For each place, get the icon, name and location.
      var bounds = new google.maps.LatLngBounds();
      places.forEach(function(place) {
        if (!place.geometry) {
          console.log("Returned place contains no geometry");
          return;
        }
        var icon = {
          url: place.icon,
          size: new google.maps.Size(71, 71),
          origin: new google.maps.Point(0, 0),
          anchor: new google.maps.Point(17, 34),
          scaledSize: new google.maps.Size(25, 25)
        };

        // Create a marker for each place.
        var image = 'http://www.instead.com.pl/target2.png';
        markers.push(new google.maps.Marker({
          map: map,
          icon: image,
          title: place.name,
          position: place.geometry.location
        }));

        if (place.geometry.viewport) {
          // Only geocodes have viewport.
          bounds.union(place.geometry.viewport);
        } else {
          bounds.extend(place.geometry.location);
        }
      });
      map.fitBounds(bounds);
    });
    google.maps.event.addListenerOnce(map, 'idle', function() {
      // inputFocus();
      setTimeout(inputFocus, 1000);
    });

  }
</script>

<script>
  function start() {
    initialize();
  }
  window.onload = start;
</script>


<input id="pac-input" class="controls" type="text" placeholder="Enter location" value="Nebraska" />

<div id="mapindex"></div>