如何在未选择自动填充选项时禁用输入:Google Maps SearchBox [英] How to disable enter when autocomplete option not selected: Google Maps SearchBox

查看:113
本文介绍了如何在未选择自动填充选项时禁用输入:Google Maps SearchBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将Google地图搜索框与自动填充功能结合使用:



如果用户输入显示结果的名称,并在选择实际结果前按Enter键,则places_matched事件仍然存在fires和API为他们选择结果。



如何强制用户选择/突出显示自动完成结果,或者至少检测到他们实际上没有选择一个结果并阻止请求?



在这里查看jsfiddle: http://jsfiddle.net/4rs1mgno/2/



在文本输入中,输入任意内容,然后按Enter键。我键入'testing'并输出BYU Testing Center。我不希望发生任何事情,因为他们实际上没有选择一个选项。



这是来自小提琴的JS代码:

  $(function(){
var input = document.getElementById('pac-input');
var options = {
keyword :'establishment'
}
var searchBox = new google.maps.places.SearchBox(input,options);

searchBox.addListener('places_changed',function(evt) {
console.log('changed');

var places = searchBox.getPlaces();

if(places.length == 0){
return;
}
places.forEach(function(place){
$('#output')。append(place ['name']);
} );
});
});

谢谢!



有很多类似的问题在这里,但没有一个匹配这个。

解决方案

你可以使用自动填充服务 Places Service 并模仿SearchBox的行为。使用 getPlacePredictions ,您可以轻松控制搜索字段和搜索结果项的行为。



此示例已有一点CSS使它看起来像SearchBox。当然,你可以适应和增强。代码被注释,因此它应该说明一切。



  var autocompleteService,placesService ,results,map; function initialize(){results = document.getElementById('results'); var mapOptions = {zoom:5,center:new google.maps.LatLng(50,50)}; map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions); //绑定侦听器以进行地址搜索google.maps.event.addDomListener(document.getElementById('address'),'input',function(){results.style.display ='block'; getPlacePredictions(document.getElementById('address ')。value);}); //在地址字段聚焦时显示结果(如果不为空)google.maps.event.addDomListener(document.getElementById('address'),'focus',function(){if(document.getElementById('address')。 value!==''){results.style.display ='block'; getPlacePredictions(document.getElementById('address')。value);}}); //当结果和输入点击发生时隐藏结果google.maps.event.addDomListener(文档,'click',function(e){if((e.target.parentElement.className!=='pac-container' )&&(e.target.parentElement.className!=='pac-item')&&(e.target.tagName!=='INPUT')){results.style.display ='none' ;}}); autocompleteService = new google.maps.places.AutocompleteService(); placesService = new google.maps.places.PlacesService(map);} //获取位置预测函数getPlacePredictions(搜索){autocompleteService.getPlacePredictions({input:search,types:['establishment','geocode']},callback); } //获取位置detailsfunction getPlaceDetails(placeId){var request = {placeId:placeId}; placesService.getDetails(request,function(place,status){if(status === google.maps.places.PlacesServiceStatus.OK){var center = place.geometry.location; var marker = new google.maps.Marker({ position:center,map:map}); map.setCenter(center); //隐藏自动填充结果results.style.display ='none';}});} //放置搜索回调函数回调(预测,状态){/ / empty results container results.innerHTML =''; //放置服务状态错误if(status!= google.maps.places.PlacesServiceStatus.OK){results.innerHTML ='< div class =pac-item pac-item-error>您的搜索未返回任何结果。状态:'+ status +'< / div>';返回; } //为每个预测构建输出(var i = 0,prediction; prediction = predictions [i]; i ++){//在结果容器中插入输出结果.innerHTML + ='< div class =pac-item data-placeid ='+ prediction.place_id +'data-name ='+ prediction.terms [0] .value +'>< span class =pac-icon pac-icon-marker> < / span>'+ prediction.description +'< / div>'; } var items = document.getElementsByClassName(pac-item); //结果项目单击为(var i = 0,item; item = items [i]; i ++){item.onclick = function(){getPlaceDetails(this.dataset.placeid); }; google.maps.event.addDomListener(window,'load',initialize);  

  body,html {font-family:Arial,sans-serif;填充:0;保证金:0;身高:100%;}#map-canvas {身高:150px;宽度:200px; margin-bottom:10px;}。search {width:200px;填充:5px; float:left;} label {display:block;宽度:160px; font-size:11px;颜色:#777; margin-bottom:5px;} input {border:1px solid #ccc;宽度:170px;填充:3px 5px; box-sizing:border-box; -moz-box-sizing:border-box; -webkit-box-sizing:border-box; box-shadow:0 2px 6px rgba(0,0,0,.1);}。pac-container {background-color:#fff; z-index:1000; border-radius:2px; font-size:11px; box-shadow:0 2px 6px rgba(0,0,0,.3); -moz-box-sizing:border-box; -webkit-box-sizing:border-box; box-sizing:border-box;溢出:隐藏;宽度:170px;}。pac-icon {width:15px;身高:20px;保证金权利:7px; margin-top:6px; display:inline-block; vertical-align:top; background-image:url(https://maps.gstatic.com/mapfiles/api-3/images/autocomplete-icons.png); background-size:34px;}。pac-icon-marker {background-position:-1px -161px;}。pac-item {cursor:pointer;填充:0 4px;文本溢出:省略号;溢出:隐藏;白色空间:nowrap;线高:30px; vertical-align:middle; text-align:left; border-top:1px solid#e6e6e6;颜色:#999;}。pac-item:hover {background-color:#efefef;}。pac-item-error,.pac-item-error:hover {color:#aaa;填充:0 5px; cursor:default; background-color:#fff;}  

 < div class = 搜索 > < label for =address>地址:< / label> < input id =addressplaceholder =输入地址type =texttabindex =1/> < br /> < div id =resultsclass =pac-container>< / div>< / div>< div id =map-canvas>< / div>< script src = https://maps.googleapis.com/maps/api/js?libraries=places>< /脚本>  


Using Google Maps Searchbox with autocomplete:

If a user enters a name that displays results, and hit Enter before selecting an actual result, the 'places_matched' event still fires and the API chooses a result for them.

How can I force the user to select/highlight an autocomplete result, or at least detect somewhere that they didn't actually select a result and block the request?

See the jsfiddle here: http://jsfiddle.net/4rs1mgno/2/

In the text input, enter anything, and hit enter. I type 'testing' and it outputs "BYU Testing Center". I want nothing to happen, since they didn't actually select an option.

Here's the JS code from the fiddle:

 $(function(){      
 var input = document.getElementById('pac-input');
    var options = {
      keyword: 'establishment'
    }
    var searchBox = new google.maps.places.SearchBox(input, options);

    searchBox.addListener('places_changed',     function(evt) {
      console.log('changed');

      var places = searchBox.getPlaces();

      if (places.length == 0) {
        return;
      }
      places.forEach(function(place) {
        $('#output').append(place['name']);
      });
    });
});

Thanks!

There are a lot of similar questions here on SO, but none that match this.

解决方案

You can use the Autocomplete Service and the Places Service and mimic the behavior of the SearchBox. Using getPlacePredictions you can easily control the behavior of your search field and the search results items.

This example already has a bit of CSS that makes it look "like" the SearchBox. You can adapt and enhance of course. The code is commented so it should speak for itself.

var autocompleteService, placesService, results, map;

function initialize() {

  results = document.getElementById('results');

  var mapOptions = {
    zoom: 5,
    center: new google.maps.LatLng(50, 50)
  };

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  // Bind listener for address search
  google.maps.event.addDomListener(document.getElementById('address'), 'input', function() {

    results.style.display = 'block';
    getPlacePredictions(document.getElementById('address').value);
  });

  // Show results when address field is focused (if not empty)
  google.maps.event.addDomListener(document.getElementById('address'), 'focus', function() {

    if (document.getElementById('address').value !== '') {

      results.style.display = 'block';
      getPlacePredictions(document.getElementById('address').value);
    }
  });

  // Hide results when click occurs out of the results and inputs
  google.maps.event.addDomListener(document, 'click', function(e) {

    if ((e.target.parentElement.className !== 'pac-container') && (e.target.parentElement.className !== 'pac-item') && (e.target.tagName !== 'INPUT')) {

      results.style.display = 'none';
    }
  });

  autocompleteService = new google.maps.places.AutocompleteService();
  placesService = new google.maps.places.PlacesService(map);
}

// Get place predictions
function getPlacePredictions(search) {

  autocompleteService.getPlacePredictions({
    input: search,
    types: ['establishment', 'geocode']
  }, callback);
}

// Get place details
function getPlaceDetails(placeId) {

  var request = {
    placeId: placeId
  };

  placesService.getDetails(request, function(place, status) {

    if (status === google.maps.places.PlacesServiceStatus.OK) {

      var center = place.geometry.location;
      var marker = new google.maps.Marker({
        position: center,
        map: map
      });

      map.setCenter(center);

      // Hide autocomplete results
      results.style.display = 'none';
    }
  });
}

// Place search callback
function callback(predictions, status) {

  // Empty results container
  results.innerHTML = '';

  // Place service status error
  if (status != google.maps.places.PlacesServiceStatus.OK) {
    results.innerHTML = '<div class="pac-item pac-item-error">Your search returned no result. Status: ' + status + '</div>';
    return;
  }

  // Build output for each prediction
  for (var i = 0, prediction; prediction = predictions[i]; i++) {

    // Insert output in results container
    results.innerHTML += '<div class="pac-item" data-placeid="' + prediction.place_id + '" data-name="' + prediction.terms[0].value + '"><span class="pac-icon pac-icon-marker"></span>' + prediction.description + '</div>';
  }

  var items = document.getElementsByClassName("pac-item");

  // Results items click
  for (var i = 0, item; item = items[i]; i++) {

    item.onclick = function() {

      getPlaceDetails(this.dataset.placeid);
    };
  }
}

google.maps.event.addDomListener(window, 'load', initialize);

body,
html {
  font-family: Arial, sans-serif;
  padding: 0;
  margin: 0;
  height: 100%;
}

#map-canvas {
  height: 150px;
  width: 200px;
  margin-bottom: 10px;
}

.search {
  width: 200px;
  padding: 5px;
  float: left;
}

label {
  display: block;
  width: 160px;
  font-size: 11px;
  color: #777;
  margin-bottom: 5px;
}

input {
  border: 1px solid #ccc;
  width: 170px;
  padding: 3px 5px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-shadow: 0 2px 6px rgba(0, 0, 0, .1);
}

.pac-container {
  background-color: #fff;
  z-index: 1000;
  border-radius: 2px;
  font-size: 11px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, .3);
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  overflow: hidden;
  width: 170px;
}

.pac-icon {
  width: 15px;
  height: 20px;
  margin-right: 7px;
  margin-top: 6px;
  display: inline-block;
  vertical-align: top;
  background-image: url(https://maps.gstatic.com/mapfiles/api-3/images/autocomplete-icons.png);
  background-size: 34px;
}

.pac-icon-marker {
  background-position: -1px -161px;
}

.pac-item {
  cursor: pointer;
  padding: 0 4px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 30px;
  vertical-align: middle;
  text-align: left;
  border-top: 1px solid #e6e6e6;
  color: #999;
}

.pac-item:hover {
  background-color: #efefef;
}

.pac-item-error,
.pac-item-error:hover {
  color: #aaa;
  padding: 0 5px;
  cursor: default;
  background-color: #fff;
}

<div class="search">
  <label for="address">Address:</label>
  <input id="address" placeholder="Enter address" type="text" tabindex="1" />
  <br />
  <div id="results" class="pac-container"></div>
</div>
<div id="map-canvas"></div>

<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>

这篇关于如何在未选择自动填充选项时禁用输入:Google Maps SearchBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆