从谷歌地理编码jquery抓住国家

我有帮助得到一个jquery脚本,它将通过谷歌地理编码系统对一个类型化的位置进行地理编码。

我需要将country_name的short_name放入country字段。 对于我的生活,我无法理解我应该如何整合,而我尝试的每件事都没有回报价值。 任何人都可以请一些正确的方法来实现这个目标吗?

JSFIDDLE: http : //jsfiddle.net/spadez/jCB4s/2/

$(function () { var input = $("#loc"), lat = $("#lat"), lng = $("#lng"), lastQuery = null, lastResult = null, // new! autocomplete; function processLocation(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() } }); }); }); 

根据API我需要这个:

 results[]: { types[]: string, formatted_address: string, address_components[]: { short_name: string, long_name: string, types[]: string }, geometry: { location: LatLng, location_type: GeocoderLocationType viewport: LatLngBounds, bounds: LatLngBounds } } 

通过结果寻找具有“国家”类型的结果

查找类型为“postal_code”的结果的示例

这样的东西应该工作(没有测试):

 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()); var address = results[0].address_components; for (var p = address.length-1; p >= 0; p--) { if (address[p].types.indexOf("country") != -1) { // do something useful with the country... // document.getElementById('postcode').innerHTML= address[p].long_name; } } 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 });