javascript 如何通过搜索按钮使用 Google Places API?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20491405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:37:01  来源:igfitidea点击:

How to use Google Places API with a search button?

javascriptgoogle-places-api

提问by raghuveer999

I am using Google Places API in my project. It is working fine when I give some input in a text box and hit "enter" on keyboard. It is showing results.

我在我的项目中使用 Google Places API。当我在文本框中输入一些内容并在键盘上点击“输入”时,它工作正常。它正在显示结果。

But, I want to place search button beside the textbox and when I press the search button, the results should be shown.

但是,我想在文本框旁边放置搜索按钮,当我按下搜索按钮时,应该显示结果。

This is my initialze function.

这是我的初始化函数。

function initialize() {
  ...
  google.maps.event.addListener(searchBox, 'places_changed', function() {

    // When I hit Enter button the execution directly comes here.
    // I don't know how to work with onClick function for this purpose.

    var places = searchBox.getPlaces();
    for (var i = 0, marker; marker = markers[i]; i++) {
      marker.setMap(null);
    }
  }
}

采纳答案by Andy

I implemented something similar recently. I needed to use two different functions; one for when places_changedis called (which already has the geolocation data) and one for when the button event is triggered which needs to manage the geolocation call to Google manually. You code might look something like this:

我最近实现了类似的东西。我需要使用两个不同的函数;一个用于何时places_changed被调用(已经有地理定位数据),另一个用于当按钮事件被触发时需要手动管理对谷歌的地理定位调用。您的代码可能如下所示:

var searchBox, map, geocoder;

function processPlacesSearch() {
  var places = searchBox.getPlaces();
  if (places.length) {
    location = places[0].geometry.location;
    var origin = new google.maps.LatLng(location.lat(), location.lng());
    // plot origin
  }
}

function processButtonSearch(location) {
  geocoder = new google.maps.Geocoder();
  geocoder.geocode(location, function (data) {
    var lat = data[0].geometry.location.lat();
    var lng = data[0].geometry.location.lng();
    var origin = new google.maps.LatLng(lat, lng);
    // plot origin
  });
}

function initialize() {
  map = new google.maps.Map(document.getElementById('map'), options);
  searchBox = new google.maps.places.SearchBox(document.getElementById('searchbox'));
  google.maps.event.addListener(searchBox, 'places_changed', processPlacesSearch);
}

var button = document.getElementById('searchbutton');
var searchbox = document.getElementById('searchbox');

button.onclick = function () {
  var location = searchbox.value;
  processButtonSearch(location);
}

回答by jsg

I don't think these answers are still in date, but this documentation helped massively for me.

我不认为这些答案仍然过时,但是这个文档对我有很大帮助。

https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

As the button passes through gecoder and the map, which then processes the search box value.

当按钮通过地理编码器和地图,然后处理搜索框值。

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

    document.getElementById('submit').addEventListener('click', function() {
      geocodeAddress(geocoder, map);
    });
  }

  function geocodeAddress(geocoder, resultsMap) {
    var address = document.getElementById('address').value;
    geocoder.geocode({'address': address}, function(results, status) {
      if (status === 'OK') {
        resultsMap.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
          map: resultsMap,
          position: results[0].geometry.location
        });
      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }
    });
  }

回答by Vadim Gremyachev

The following example demonstrates how to:

以下示例演示了如何:

  • place a search button next to the search box

  • display results once the button clicked(instead of standard behavior when it is displayed once the item is selected from Place Autocomplete)

  • 在搜索框旁边放置一个搜索按钮

  • 单击按钮后显示结果(而不是从Place Autocomplete选择项目后显示的标准行为)

function initAutocomplete() {
    var map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: -33.8688, lng: 151.2195 },
        zoom: 13,
        mapTypeId: 'roadmap'
    });

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

    // 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 () {
        //displaySearchResults(map, searchBox, markers);
    });

    
    searchBtn.onclick = function () {
        displaySearchResults(map,searchBox,markers);
    }
}



function displaySearchResults(map, searchBox, markers) {
    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);
}

initAutocomplete();
html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
      .controls {
        margin-top: 10px;
        border: 1px solid transparent;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        height: 32px;
        outline: none;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
      }

      #pac-input {
        background-color: #fff;
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
        margin-left: 12px;
        padding: 0 11px 0 13px;
        text-overflow: ellipsis;
        width: 300px;
      }

      #pac-input:focus {
        border-color: #4d90fe;
      }

      .pac-container {
        font-family: Roboto;
      }

      #type-selector {
        color: #fff;
        background-color: #4d90fe;
        padding: 5px 11px 0px 11px;
      }

      #type-selector label {
        font-family: Roboto;
        font-size: 13px;
        font-weight: 300;
      }
      #target {
        width: 345px;
      }


button[id="search-button"] {
    margin-left: -50px;
    margin-top: 10px;
    height: 32px;
    width: 50px;
    background: blue;
    color: white;
    border: 0;
    -webkit-appearance: none;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.css" />
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<button id="search-button" class="icon"><i class="fa fa-search"></i></button>
<div id="map"></div>