2013-05-13 86 views
0

我试图优化我的地理编码脚本并不在于它的实际工作,我想知道,如果当用户选择从下拉的自我暗示有可能实际启动地理编码。谷歌地图地理编码 - 在自动提示地理编码点击

这样的地理编码将是用户点击搜索按钮的时间完成,并且他们不会等待。当用户点击自动创建的位置时,是否可以使用某种事件触发地理编码?

这是代码

http://jsfiddle.net/sR4GR/22/ 

原始的Javascript

 <script type="text/javascript" src="//maps.google.com/maps/api/js?sensor=true&libraries=places"></script> 
<script type="text/javascript"> 
    // SET COOKIE FOR TESTING 
    $.cookie("country", "UK"); 

    // GEOCODE RESULT 
    function geocode() { 

     var GeoCoded = { 
      done: false 
     }; 
     var input = document.getElementById('loc'); 
     var options = { 
      types: ['geocode'] 
     }; 
     var country_code = $.cookie('country'); 
     if (country_code) { 
      options.componentRestrictions = { 
       'country': country_code 
      }; 
     } 
     var autocomplete = new google.maps.places.Autocomplete(input, options); 
     $('#searchform').on('submit', function(e) { 
      if (GeoCoded.done) return true; 
      e.preventDefault(); 
      var geocoder = new google.maps.Geocoder(); 
      var address = document.getElementById('loc').value; 
      $('#searchform input[type="submit"]').attr('disabled', true); 
      geocoder.geocode({ 
       'address': address 
      }, 

      function(results, status) { 
       if (status == google.maps.GeocoderStatus.OK) { 
        $('#lat').val(results[0].geometry.location.lat()); 
        $('#lng').val(results[0].geometry.location.lng()); 
        GeoCoded.done = true; 
        $.cookie("location_input", $("#loc").val()); 
        $.cookie("lng", $("#lng").val()); 
        $.cookie("lat", $("#lat").val()); 
        $('#searchform').submit(); 
       } else { 
        $('#searchform input[type="submit"]').attr('disabled', false); 
        alert("We couldn't find this location") 
       } 

      }); 

     }); 

    }; 
</script> 


<body onload="geocode()"> 
    <form id="searchform"> 
     <input class="kw" id="keyword" placeholder="Keyword"></input> 
     <input id="loc" placeholder="Location" type="text"></input> 
     <input type="submit" value="Search" id="search"> 
     <input class="hidden" id="lat" disabled="true" placeholder="lat"></input> 
     <input class="hidden" id="lng" disabled="true" placeholder="lng"></input> 
    </form> 

回答

1

您可以事件处理程序绑定到自动完成” S“place_changed”事件

google.maps.event.addListener(autocomplete, 'place_changed', function() { 
    //initiate the geocode 
}); 

你可以阅读一下here

+0

那看起来就是我所追求的,除非我无法实现它。对于我的例子,它不应该像这样简单吗? google.maps.event.addListener(autocomplete,'place_changed',function(){ geocode() }); – Jimmy 2013-05-13 12:02:54

+0

没有,要定义地理编码函数内部自动完成,你不能事件处理程序的定义之前绑定到它,我想你应该把这个事件处理程序自动完成创建后马上使用您在申请提交searchform – paulitto 2013-05-13 12:09:19

+0

相同的功能,我认为你的说明是正确的,但我不能得到它的工作,我是新来的JavaScript,似乎这东西是有点高于我。这是我试过的:http://jsfiddle.net/sR4GR/23/ – Jimmy 2013-05-13 12:15:41

0

我建议你使用jQuery的自动完成功能的Widget,并获取来自谷歌的数据作为源数据jQuery的自动完成

+0

谢谢您的答复,但这个不能过滤器的基础上的国家,这是一个真正的耻辱,但是它停止我能够使用它 – Jimmy 2013-05-13 11:50:33