编程语言
首页 > 编程语言> > javascript – 如何将Google Places API与搜索按钮结合使用?

javascript – 如何将Google Places API与搜索按钮结合使用?

作者:互联网

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

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

这是我的初始化功能.

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

解决方法:

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

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

标签:javascript,google-places-api
来源: https://codeday.me/bug/20190831/1774336.html