Симуляция автозаполнения при нажатии на Google Maps

В настоящее время у меня есть следующая функция, которая выполняется, когда Ajax завершает работу на моей странице, которая затем загружается в тексте (на данный момент), а затем вызывает диалоговое окно автозаполнения.

    <script type="text/javascript"> $(document).ajaxComplete(function() {
    jQuery('#facetwp-location').val('Richmond, Vic'); // populate the input box
    google.maps.event.trigger( document.querySelector('#facetwp-location'), 'focus', {} ); // force the autocomplete to show
    });

</script>

Мне нужно сделать следующее:

  1. Получите информацию о местоположении пользователя из поля BuddyPress Xprofile (которое заменит заранее написанный текст)
  2. Автоматически загружать первый элемент в списке автозаполнения (т.е. имитировать нажатие клавиши и Enter в отображаемом списке.

Еще раз, мне не хватает навыков jQuery, и мне нужна небольшая помощь для выполнения этой функции.

Я работал над этим, и до сих пор у меня есть это - но он все еще не завершен

function get_user_location_for_facet_load(){
if (is_page(2101)) {
?>
<script type="text/javascript"> 
$(function() { 
$(document).ajaxStop(function() {
jQuery('#facetwp-location').val('<?php
$user_id = bp_loggedin_user_id();
echo xprofile_get_field_data('Suburb',$user_id);
?>'); // populate the input box
$('#facetwp-location').focus();
google.maps.event.trigger( document.querySelector('#facetwp-location'), 'focus', {} ); // force the autocomplete to show
$( ".pac-container .pac-item:first" ).promise().done(function() {
google.maps.event.trigger( document.querySelector('.pac-container .pac-item'), 'focus', {} ); 
 google.maps.event.trigger(document.querySelector('.pac-container .pac-item'), 'keydown', {
        keyCode: 13
    });

//var txt = $('#facetwp-location').val();
//alert(txt);
});
});
});
</script>
<?php
}

Не уверен, что я ближе, но может ли кто-нибудь помочь.


person Brett Canfield    schedule 16.03.2017    source источник


Ответы (1)


Ваш код выглядит правильно, но попробуйте заключить его в $ .ready (), например,

$(function() { // enclose your ajax complete in document ready function
    $(document).ajaxComplete(function() {
       jQuery('#facetwp-location').val('Richmond, Vic'); // populate the input box
       google.maps.event.trigger( document.querySelector('#facetwp-location'), 'focus', {} ); // force the autocomplete to show
    });
});

В качестве альтернативы попробуйте использовать .keypress () для ввода и запустить карты Google в его обработчике, например

$(function() { // enclose your ajax complete in document ready function
    $(document).ajaxComplete(function() {
       jQuery('#facetwp-location').val('Richmond, Vic').keypress(function(){
          google.maps.event.trigger(this, 'focus', {} ); // force the autocomplete to show
       });
       jQuery('#facetwp-location').trigger('keypress');
    });
});

Обновлено с помощью кода Google,

 $(function() {
   var lat = -33.8688,
     lng = 151.2195,
     latlng = new google.maps.LatLng(lat, lng),
     image = 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png';

   var mapOptions = {
       center: new google.maps.LatLng(lat, lng),
       zoom: 13,
       mapTypeId: google.maps.MapTypeId.ROADMAP
     },
     map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions),
     marker = new google.maps.Marker({
       position: latlng,
       map: map,
       icon: image
     });

   var input = document.getElementById('facetwp-location');
   var autocomplete = new google.maps.places.Autocomplete(input, {
     types: ["geocode"]
   });

   autocomplete.bindTo('bounds', map);
   var infowindow = new google.maps.InfoWindow();

   google.maps.event.addListener(autocomplete, 'place_changed', function() {
     infowindow.close();
     var place = autocomplete.getPlace();
     if (place.geometry.viewport) {
       map.fitBounds(place.geometry.viewport);
     } else {
       map.setCenter(place.geometry.location);
       map.setZoom(17);
     }

     moveMarker(place.name, place.geometry.location);
   });

   $("#facetwp-location").focus(function() {
     selectFirstResult();
   });


   function selectFirstResult() {
     infowindow.close();
     $(".pac-container").hide();
     var firstResult = $('#facetwp-location').val();
     var geocoder = new google.maps.Geocoder();
     geocoder.geocode({
       "address": firstResult
     }, function(results, status) {
       if (status == google.maps.GeocoderStatus.OK) {
         var lat = results[0].geometry.location.lat(),
           lng = results[0].geometry.location.lng(),
           placeName = results[0].address_components[0].long_name,
           latlng = new google.maps.LatLng(lat, lng);

         moveMarker(placeName, latlng);
       }
     });
   }

   function moveMarker(placeName, latlng) {
     marker.setIcon(image);
     marker.setPosition(latlng);
     infowindow.setContent(placeName);
     infowindow.open(map, marker);
   }

   $('#facetwp-location').trigger('focus');
 });
#map_canvas {
  width: 100%;
  height: 400px;
  background-color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCsaZtFeCU6YCKI_1D_tJ73JzARq9j6zaY&libraries=places"></script>
<input id="facetwp-location" value="Richmond, Vic" type="text" size="50" />
<div id="map_canvas"></div>

person Rohan Kumar    schedule 16.03.2017
comment
Это не добавило никаких реальных функциональных изменений и не включает никаких имитированных нажатий клавиш, позволяющих автозаполнению для отправки и поиска. - person Brett Canfield; 16.03.2017
comment
Попробуйте мой обновленный ответ и альтернативный вариант. Надеюсь, это сработает для вас. - person Rohan Kumar; 16.03.2017
comment
Это по-прежнему не отправляет нажатие клавиши в браузер, что я и пытаюсь сделать, чтобы пользователь ничего не нажимал. Это не закрывает никаких других предложений, касающихся API автозаполнения Карт Google и того, что необходимо сделать, чтобы заставить его отправить (например, нажмите клавишу со стрелкой вниз, а затем нажмите ENTER, чтобы выбрать первое место в списке) - person Brett Canfield; 17.03.2017
comment
Я работал над этим, и до сих пор у меня есть это - но он все еще не завершен - person Brett Canfield; 20.03.2017
comment
Это то, что я могу сделать до сих пор - я хочу, чтобы ввод отправлялся автоматически, чтобы он мог обновлять страницу ссылка - person Brett Canfield; 20.03.2017
comment
Спасибо за вашу помощь, Рохан, но меня попросили больше не размещать это на сайте. Спасибо за вашу помощь. - person Brett Canfield; 22.03.2017