网页加载时Google Place自动搜索不适用于URL中的点

时间:2018-07-20 15:03:23

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

我有一个网站:

  1. 加载Google地图。
  2. 使用Google地方信息搜索所使用的input方法在$_GET字段中获取一些值。
  3. autofocus字段上获取input
  4. 然后在页面加载时执行自动搜索。

我可以从数据库数据中建立的链接的方案是:

example.com?local=52.6762,19.7582 (i.e. lat, lng).

下面的代码仅在不使用URL内的点号的情况下才有效。因此,例如,如果我使用example.com?local=52,19,那么代码将按照我希望的那样工作。

但是通过example.com?local=52.6,19.7之类的链接,它似乎停止在步骤3上。

我认为该错误可能位于负责步骤4的代码的内部,即:

itemsloaded = google.maps.event.addDomListener(document.body, 'DOMNodeInserted', function(e) {
  google.maps.event.trigger(input, 'keydown', {
    keyCode: 13
  })
});

也许您在项目中遇到了这个问题。请帮忙。

代码:

<!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=yourapikeyhere&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);
      });

      // trigger tha autofocus function with timeout
      google.maps.event.addListenerOnce(map, 'idle', function() {
        // inputFocus();
        setTimeout(inputFocus, 1000);
      });
      // force autosearch on page load
      itemsloaded = google.maps.event.addDomListener(document.body, 'DOMNodeInserted', function(e) {
        google.maps.event.trigger(input, 'keydown', {
          keyCode: 13
        })
      });
    }
  </script>
  <script>
    function start() {
      initialize();
    }
    window.onload = start;
  </script>
</head>
<body>
  <input id="pac-input" class="controls" type="text" placeholder="Enter location" onload="mouseEnter()" value="<?php if(isset ($_GET['local'])){ echo $_GET['local'];}?>" />
  <div id="mapindex"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

这是您的代码的有效简化版本。

从地图idle事件中触发输入字段的焦点和按下键就足够了。无需设置超时等。

同样是AFAIK,在API URL中传递types=(cities)无效。

因此,如果我这样称呼此页面:map.php?local=52.6762,19.7582,则地图将以这些坐标为中心,并显示一个标记。

<!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>
  <!-- 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);
      });

      // trigger tha autofocus function
      google.maps.event.addListenerOnce(map, 'idle', function() {
        input.focus();
        google.maps.event.trigger(input, 'keydown', {
          keyCode: 13
        })
      });
    }
  </script>
</head>
<body>
  <input id="pac-input" class="controls" type="text" placeholder="Enter location" onload="mouseEnter()" value="<?php if (isset ($_GET['local'])) {
      echo $_GET['local'];
    } ?>" />
  <div id="mapindex"></div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initialize" async defer></script>
</body>
</html>