本文主要是介绍[google Autocomplete API 调用 查询 address,city,state],希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
主要功能:调用google Autocomplete api 完成如下图功能。
第一步 页面调用 google api
【https://maps.googleapis.com/maps/api/js?key=" + GoogleAPIKey + "&libraries=places&callback=InitAutocompleteCityState&language=en】
GoogleAPIKey:为自己访问【https://console.cloud.google.com/apis/dashboard】申请的google apikey,每天有免费额度。
google doc:
第二步 需要用到的几个function
【callback=InitAutocompleteCityState】
InitAutocompleteCityState: function () {var OptionsCity = {types: ["(cities)"], componentRestrictions: { country: "us" },fields: ["formatted_address", "address_components"], //"address_components", "geometry", "icon",};CityAutocomplete = new google.maps.places.Autocomplete((document.getElementById('Input_SearchCityState')), OptionsCity);CityAutocomplete.addListener('place_changed', function () { Detail.FillInGoogleAddress('B', CityAutocomplete); });}
FillInGoogleAddress
FillInGoogleAddress: function (tp, acomplete) {$("#Input_" + tp + "_route").val('');$("#Input_" + tp + "_zipcode").val('');$("#Input_" + tp + "_city").val('');$("#Input_" + tp + "_county").val('');$("#Input_" + tp + "_state").val('');$("#Input_" + tp + "_country").val('');var place = acomplete.getPlace();if (place != undefined && place.address_components != undefined) {//addressvar vraddress = place.address_components.find(function (e) { return e.types[0] == "route" });if (vraddress != undefined) {$("#Input_" + tp + "_route").val(vraddress.short_name);}//zipcodevar vrzipcode = place.address_components.find(function (e) { return e.types[0] == "postal_code" });if (vrzipcode != undefined) {$("#Input_" + tp + "_zipcode").val(vrzipcode.short_name);}//cityvar vrcity = place.address_components.find(function (e) { return e.types[0] == "locality" });if (vrcity != undefined) {$("#Input_" + tp + "_city").val(vrcity.short_name);}//countyvar vrcounty = place.address_components.find(function (e) { return e.types[0] == "administrative_area_level_2" });if (vrcounty != undefined) {$("#Input_" + tp + "_county").val(vrcounty.short_name);}//statevar vrstate = place.address_components.find(function (e) { return e.types[0] == "administrative_area_level_1" });if (vrstate != undefined) {$("#Input_" + tp + "_state").val(vrstate.short_name);}//countryvar vrcountry = place.address_components.find(function (e) { return e.types[0] == "country" });if (vrcountry != undefined) {$("#Input_" + tp + "_country").val(vrcountry.short_name);}}
html:
<input id="Input_SearchCityState" type="text" />
这篇关于[google Autocomplete API 调用 查询 address,city,state]的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!