首页 > 解决方案 > 谷歌使用输入字段映射 API JS 多个标记?

问题描述

当我在网站上的搜索框中插入内容时,我希望能够显示多个标记。现在我有 3 个要增加的输入字段。这就是我目前所拥有的,我尝试将多个 searchBox 值存储在var这样的位置:var markers = searchBox.getPlaces(), searchBox.getPlaces1(), searchBox.getPlaces2()

如何将此代码扩展到其他输入字段?

<input id="pac-input" class="controls" type="text" placeholder="Search Box" /><br />
<input id="pac-input1" class="controls" type="text" placeholder="Search Box" />
<input id="pac-input2" class="controls" type="text" placeholder="Search box" />
<div id="map"></div>
<script>
    function initAutocomplete() {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: { lat: 52.728616, lng: 6.4901 },
            zoom: 13,
            mapTypeId: 'roadmap'
        });

        // Create the search box and link it to the UI element.
        var input = document.getElementById('pac-input');
        var input1 = document.getElementById('pac-input1');
        var input2 = document.getElementById('pac-input2');
        var searchBox = new google.maps.places.SearchBox(input);
        var searchBox1 = new google.maps.places.SearchBox(input1);
        var searchBox2 = new google.maps.places.SearchBox(input2);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input1);

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

        var markers = [];

        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.
                markers.push(new google.maps.Marker({
                    map: map,
                    icon: icon,
                    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 src="https://maps.googleapis.com/maps/api/js?key=[APIKEY]&libraries=places&callback=initAutocomplete"
        async defer></script>

标签: javascriptapigoogle-mapsgoogle-maps-api-3maps

解决方案


相关问题(用于自动完成):Google Maps API 自动完成同一页面上的第二个地址字段

获取<input>要用于 的元素数组SearchBox,使用这些元素创建SearchBox对象,创建一个函数,该函数采用唯一标识符SearchBox和对对象的引用SearchBox。使用该函数处理来自每个SearchBox对象的事件。

var searchBoxes = document.getElementsByClassName('controls');
for (var i=0; i<searchBoxes.length;i++) {
  var searchBox = new google.maps.places.SearchBox(searchBoxes[i]);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(searchBoxes[i]);
  map.addListener('bounds_changed', function() {
    searchBox.setBounds(map.getBounds());
  });
  markers.push([]);
  searchBox.addListener('places_changed', (function(i) {
    return function() {
      processSearch(i, this)
    }
  }(i)));
}

流程搜索功能:

function processSearch(uniqueId, searchBox) {
  var places = searchBox.getPlaces();

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

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

  // 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.
    if (!markers[uniqueId]) markers.push([]);
    markers[uniqueId].push(new google.maps.Marker({
      map: map,
      icon: icon,
      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);
}

概念证明小提琴

结果地图的屏幕截图

代码片段:

html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

.controls {
  width: 100px;
}
<input id="pac-input" class="controls" type="text" placeholder="Search Box" />
<input id="pac-input1" class="controls" type="text" placeholder="Search Box" />
<input id="pac-input2" class="controls" type="text" placeholder="Search box" />
<input id="pac-input3" class="controls" type="text" placeholder="Search box" />
<input id="pac-input4" class="controls" type="text" placeholder="Search box" />
<input id="pac-input5" class="controls" type="text" placeholder="Search box" />

<div id="map"></div>
<script>
  function initAutocomplete() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: {
        lat: 52.728616,
        lng: 6.4901
      },
      zoom: 13,
      mapTypeId: 'roadmap'
    });
    var markers = [];

    // Create the search boxs and link them to the UI elements.
    var searchBoxes = document.getElementsByClassName('controls');
    for (var i = 0; i < searchBoxes.length; i++) {
      var searchBox = new google.maps.places.SearchBox(searchBoxes[i]);
      map.controls[google.maps.ControlPosition.TOP_LEFT].push(searchBoxes[i]);
      map.addListener('bounds_changed', function() {
        searchBox.setBounds(map.getBounds());
      });
      markers.push([]);
      searchBox.addListener('places_changed', (function(i) {
        return function() {
          processSearch(i, this)
        }
      }(i)));
    }

    function processSearch(uniqueId, searchBox) {
      var places = searchBox.getPlaces();

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

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

      // 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.
        if (!markers[uniqueId]) markers.push([]);
        markers[uniqueId].push(new google.maps.Marker({
          map: map,
          icon: icon,
          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 src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initAutocomplete" async defer></script>


推荐阅读