谷歌地图自动完成地址点击

时间:2013-04-02 11:15:28

标签: google-maps autocomplete

我有一张谷歌地图和一个自动完整的文本框,用户开始输入,地址显示在下拉列表中,然后地图缩放到最终选择的地图。到目前为止,我对我所拥有的东西感到非常高兴。问题是,用户必须单击列表中的地址才能使其正常工作。

我想要的也是这个选项:当用户点击键盘上的“ENTER”时,即使它们没有完全填写auto_complete框,列表中的第一个地址也会自动选中,并且地图会缩放到这一点。

我正在玩

$(autocomplete).trigger("click");

但我无法修复它。所以,如果你能帮助我,我将不胜感激......我的代码是:

<script type="text/javascript">
  function initialize_google_maps() {



    var midOfIreland = new google.maps.LatLng(53.252069, -7.860718);
    var myOptions = {
      zoom: 7,
      center: midOfIreland,
      mapTypeId: google.maps.MapTypeId.ROADMAP, // ROADMAP, SATELLITE, HYBRID
      streetViewControl: false
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var input = document.getElementById('address_autocomplete');
    var options = {
      types: ['geocode']
    };

   autocomplete = new google.maps.places.Autocomplete(input, options);
    autocomplete.bindTo('bounds', map);
    // $(autocomplete).trigger("click");

    var contentstring = $('#info_window').html();


var infowindow = new google.maps.InfoWindow({content: contentstring, width:1, height:1});
// for the 'x', to close the infoWindow, we give it the same behaviour as the 'No' link, in the infoWindow
google.maps.event.addListener(infowindow, 'closeclick', function() {   
  $(".map-no-link").trigger("click");
});  


   var marker = new google.maps.Marker({
      map: map
    });



    google.maps.event.addListener(autocomplete, 'place_changed', function() {
      var place = autocomplete.getPlace();
      if (place.geometry.viewport) {
          map.fitBounds(place.geometry.viewport);
      } else {
          map.setCenter(place.geometry.location);
          map.setZoom(11);
      }
      marker.setPosition(place.geometry.location);
      $('#user_lat').val(place.geometry.location.lat());
      $('#user_lng').val(place.geometry.location.lng());
      $('#changed').val('1');

   //   infowindow.setContent(place.name);
      infowindow.open(map, marker);
    });

    <% if current_user.address and current_user.lat %>
      var currentlatlng = new google.maps.LatLng(<%= current_user.lat %>, <%= current_user.lng %>);
      var marker = new google.maps.Marker({map: map, position: currentlatlng});
      map.setCenter(currentlatlng);
      map.setZoom(11);
    <% end %>

  }

  $(function() {
      initialize_google_maps();
  });

</script>

2 个答案:

答案 0 :(得分:3)

检查jsFiddle。您需要做的是在按下Enter时收听,从自动完成容器中取出第一个项目,对其进行地理编码并处理结果。

$(document).keypress(function (e) {
  if (e.which == 13) {
    var firstResult = $(".pac-container .pac-item:first").text();
    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);
        $("input").val(firstResult);
      }
    });
  }
});

答案 1 :(得分:1)

这是我最终使用的代码,有效:

<script type="text/javascript">
  var pac_input = document.getElementById('address_autocomplete');

  (function pacSelectFirst(input){
    // store the original event binding function
    var _addEventListener = (input.addEventListener) ? input.addEventListener : input.attachEvent;

    function addEventListenerWrapper(type, listener) {
      // Simulate a 'down arrow' keypress on hitting 'return' when no pac suggestion is selected,
      // and then trigger the original listener.
      if (type == "keydown") {
        var orig_listener = listener;
        listener = function (event) {
          var suggestion_selected = $(".pac-item.pac-selected").length > 0;
          if (event.which == 13 && !suggestion_selected) {
            event.preventDefault();
            var simulated_downarrow = $.Event("keydown", {keyCode:40, which:40})
            orig_listener.apply(input, [simulated_downarrow]);
          }

          orig_listener.apply(input, [event]);
        };
      }

      // add the modified listener
      _addEventListener.apply(input, [type, listener]);
    }

    if (input.addEventListener)
      input.addEventListener = addEventListenerWrapper;
    else if (input.attachEvent)
      input.attachEvent = addEventListenerWrapper;

  })(pac_input);

  function initialize_google_maps() {
    var midOfIreland = new google.maps.LatLng(53.252069, -7.860718);
    var myOptions = {
      zoom: 7,
      center: midOfIreland,
      mapTypeId: google.maps.MapTypeId.ROADMAP, // ROADMAP, SATELLITE, HYBRID
      streetViewControl: false
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var options = {
      types: ['geocode']
    };

    autocomplete = new google.maps.places.Autocomplete(pac_input, options);
    autocomplete.bindTo('bounds', map);
    // $(autocomplete).trigger("click");

    var contentstring = $('#info_window').html();

    var infowindow = new google.maps.InfoWindow({content: contentstring, width:1, height:1});
    // for the 'x', to close the infoWindow, we give it the same behaviour as the 'No' link, in the infoWindow
    google.maps.event.addListener(infowindow, 'closeclick', function() {   
      $(".map-no-link").trigger("click");
    });  

    var marker = new google.maps.Marker({
      map: map
    });

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

      marker.setPosition(place.geometry.location);
      $('#user_lat').val(place.geometry.location.lat());
      $('#user_lng').val(place.geometry.location.lng());
      $('#changed').val('1');

      //infowindow.setContent(place.name);
      infowindow.open(map, marker);
    });

    <% if current_user.address and current_user.lat %>
      var currentlatlng = new google.maps.LatLng(<%= current_user.lat %>, <%= current_user.lng %>);
      var marker = new google.maps.Marker({map: map, position: currentlatlng});
      map.setCenter(currentlatlng);
      map.setZoom(11);
    <% end %>

  }

  $(function() {
      initialize_google_maps();
  });
</script>