最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - google places api autocomplete - adding click event - Stack Overflow

programmeradmin3浏览0评论

I'm appending a Search Results to the google places javascript api autoplete.

So far I'm doing this:

var autoplete;  
  function initialize() {
    var myLatlng = new google.maps.LatLng(40.738793, -73.991402);
    autoplete = new google.maps.places.Autoplete(document.getElementById('autoplete'));
  }

later on I have this:

$('.pac-container').append( '<div class="j-search pac-item-refresh">Search Results</div>' );

$(document.body).on('click', '.pac-container .j-search', function(e) {
    console.log('click fired');
});

The problem? The click event never fires...

Any idea why? Anything wrong with my code?

I'm appending a Search Results to the google places javascript api autoplete.

So far I'm doing this:

var autoplete;  
  function initialize() {
    var myLatlng = new google.maps.LatLng(40.738793, -73.991402);
    autoplete = new google.maps.places.Autoplete(document.getElementById('autoplete'));
  }

later on I have this:

$('.pac-container').append( '<div class="j-search pac-item-refresh">Search Results</div>' );

$(document.body).on('click', '.pac-container .j-search', function(e) {
    console.log('click fired');
});

The problem? The click event never fires...

Any idea why? Anything wrong with my code?

Share Improve this question asked Oct 8, 2013 at 14:44 DarkagelinkDarkagelink 6451 gold badge8 silver badges16 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 15

It seems that the click-event for .pac-container is cancelled by the Autoplete-instance. Use mousedown instead.

You can follow the this article. Implement and Optimize Autoplete with Google Places API Specifically Autopletion using the AutopleteService: link: JS Filddle Of AutopletionService

function debounce(func, wait, immediate) {
  let timeout;
  return function() {
    let context = this,
      args = arguments;
    let later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    let callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
}

function initAutoplete() {
  let map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 48,
      lng: 4
    },
    zoom: 4,
    disableDefaultUI: true
  });

  // Create the search box and link it to the UI element.
  let inputContainer = document.querySelector('autoplete-input-container');
  let autoplete_results = document.querySelector('.autoplete-results');
  let service = new google.maps.places.AutopleteService();
  let serviceDetails = new google.maps.places.PlacesService(map);
  let marker = new google.maps.Marker({
    map: map
  });
  let displaySuggestions = function(predictions, status) {
    if (status != google.maps.places.PlacesServiceStatus.OK) {
      alert(status);
      return;
    }
    let results_html = [];
    predictions.forEach(function(prediction) {
      results_html.push(`<li class="autoplete-item" data-type="place" data-place-id=${prediction.place_id}><span class="autoplete-icon icon-localities"></span>                   <span class="autoplete-text">${prediction.description}</span></li>`);
    });
    autoplete_results.innerHTML = results_html.join("");
    autoplete_results.style.display = 'block';
    let autoplete_items = autoplete_results.querySelectorAll('.autoplete-item');
    for (let autoplete_item of autoplete_items) {
      autoplete_item.addEventListener('click', function() {
        let prediction = {};
        const selected_text = this.querySelector('.autoplete-text').textContent;
        const place_id = this.getAttribute('data-place-id');
        let request = {
          placeId: place_id,
          fields: ['name', 'geometry']
        };

        serviceDetails.getDetails(request, function(place, status) {
          if (status == google.maps.places.PlacesServiceStatus.OK) {
            if (!place.geometry) {
              console.log("Returned place contains no geometry");
              return;
            }
            var bounds = new google.maps.LatLngBounds();
            marker.setPosition(place.geometry.location);
            if (place.geometry.viewport) {
              bounds.union(place.geometry.viewport);
            } else {
              bounds.extend(place.geometry.location);
            }
            map.fitBounds(bounds);
          }
          autoplete_input.value = selected_text;
          autoplete_results.style.display = 'none';
        });
      })
    }
  };
  let autoplete_input = document.getElementById('my-input-autoplete');
  autoplete_input.addEventListener('input', debounce(function() {
    let value = this.value;
    value.replace('"', '\\"').replace(/^\s+|\s+$/g, '');
    if (value !== "") {
      service.getPlacePredictions({
        input: value
      }, displaySuggestions);
    } else {
      autoplete_results.innerHTML = '';
      autoplete_results.style.display = 'none';
    }
  }, 150));
}

document.addEventListener("DOMContentLoaded", function(event) {
  initAutoplete();
});
#map {
  height: 100%;
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.autoplete-input-container {
  position: absolute;
  z-index: 1;
  width: 100%;
}

.autoplete-input {
  text-align: center;
}

#my-input-autoplete {
  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.16), 0 0 0 1px rgba(0, 0, 0, 0.08);
  font-size: 15px;
  border-radius: 3px;
  border: 0;
  margin-top: 10px;
  width: 290px;
  height: 40px;
  text-overflow: ellipsis;
  padding: 0 1em;
}

#my-input-autoplete:focus {
  outline: none;
}

.autoplete-results {
  margin: 0 auto;
  right: 0;
  left: 0;
  position: absolute;
  display: none;
  background-color: white;
  width: 320px;
  padding: 0;
  list-style-type: none;
  margin: 0 auto;
  border: 1px solid #d2d2d2;
  border-top: 0;
  box-sizing: border-box;
}

.autoplete-item {
  padding: 5px 5px 5px 35px;
  height: 26px;
  line-height: 26px;
  border-top: 1px solid #d9d9d9;
  position: relative;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.autoplete-icon {
  display: block;
  position: absolute;
  top: 7px;
  bottom: 0;
  left: 8px;
  width: 20px;
  height: 20px;
  background-repeat: no-repeat;
  background-position: center center;
}

.autoplete-icon.icon-localities {
  background-image: url(https://images.woosmap./icons/locality.svg);
}

.autoplete-item:hover .autoplete-icon.icon-localities {
  background-image: url(https://images.woosmap./icons/locality-selected.svg);
}

.autoplete-item:hover {
  background-color: #f2f2f2;
  cursor: pointer;
}
.autoplete-results::after {
    content: "";
    padding: 1px 1px 1px 0;
    height: 18px;
    box-sizing: border-box;
    text-align: right;
    display: block;
    background-image: url(https://maps.gstatic./mapfiles/api-3/images/powered-by-google-on-white3_hdpi.png);
    background-position: right;
    background-repeat: no-repeat;
    background-size: 120px 14px
}
<div class="autoplete-input-container">
  <div class="autoplete-input">
    <input id="my-input-autoplete" placeholder="AutopleteService" autoplete="off" role="bobox">
  </div>
  <ul class="autoplete-results">
  </ul>
</div>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis./maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback"></script>

发布评论

评论列表(0)

  1. 暂无评论