0

我是 JavaScript 新手。我一直在尝试设计一些代码,这些代码在点击搜索按钮时对位置进行地理编码,如果成功则提交表单。为了让它稍微复杂一点,如果选择了自动建议中的一个选项,它甚至在点击搜索按钮之前也会对其进行地理编码。

这一切似乎都有效,除了表单从未提交,我不知道为什么。

链接:http: //jsfiddle.net/sR4GR/42/

$(function () {
  var input = $("#loc"),
      lat   = $("#lat"),
      lng   = $("#lng"),
      lastQuery  = null,
      lastResult = null, // new!
      autocomplete;
  
  function processLocation(query, callback) { // accept a callback argument
    var query = $.trim(input.val()),
        geocoder;
  
    // if query is empty or the same as last time...
    if( !query || query == lastQuery ) {
      callback(lastResult); // send the same result as before
      return; // and stop here
    }
  
    lastQuery = query; // store for next time
  
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({ address: query }, function(results, status) {
      if( status === google.maps.GeocoderStatus.OK ) {
        lat.val(results[0].geometry.location.lat());
        lng.val(results[0].geometry.location.lng());
        lastResult = true; // success!
      } else {
        alert("Sorry - We couldn't find this location. Please try an alternative");
        lastResult = false; // failure!
      }
      callback(lastResult); // send the result back
    });
  }
  
  autocomplete = new google.maps.places.Autocomplete(input[0], {
    types: ["geocode"],
    componentRestrictions: {
      country: "uk"
    }
  });
  
  google.maps.event.addListener(autocomplete, 'place_changed', processLocation);
  
  $('#searchform').on('submit', function (event) {
    var form = this;
    
    event.preventDefault(); // stop the submission
    
    processLocation(function (success) {
      if( success ) { // if the geocoding succeeded, submit the form
        form.submit()
      }
    });
    
  });
}); 
4

1 回答 1

2

你在打电话:

processLocation(function (success) {

但是您的 processLocation 在第二个参数上有回调:

function processLocation(query, callback)

尝试从 processLocation 中删除查询参数:

function processLocation(callback)

使用空白参数调用它:

processLocation(null, function (success) 
于 2013-05-17T14:53:54.763 回答