javascript - How to generate google autocomplete address api dynamically -
i need generate n number address grabber , formatted output in json, can via ajax on button click. not getting how can use google api generate autocomplete dynamically , things separately.
i need show same type of design attached in fiddle.
initialize(); var placesearch, autocomplete; var componentform = { street_number: 'short_name', route: 'long_name', locality: 'long_name', administrative_area_level_1: 'short_name', country: 'long_name', postal_code: 'short_name' }; function initialize() { autocomplete = new google.maps.places.autocomplete( /** @type {htmlinputelement} */(document.getelementbyid('autocomplete')), { types: ['geocode'] }); google.maps.event.addlistener(autocomplete, 'place_changed', function() { fillinaddress(); }); } function fillinaddress() { var place = autocomplete.getplace(); (var component in componentform) { document.getelementbyid(component).value = ''; document.getelementbyid(component).disabled = false; } (var = 0; < place.address_components.length; i++) { var addresstype = place.address_components[i].types[0]; if (componentform[addresstype]) { var val = place.address_components[i][componentform[addresstype]]; document.getelementbyid(addresstype).value = val; } } } function geolocate() { if (navigator.geolocation) { navigator.geolocation.getcurrentposition(function(position) { var geolocation = new google.maps.latlng( position.coords.latitude, position.coords.longitude); autocomplete.setbounds(new google.maps.latlngbounds(geolocation, geolocation)); }); } }
currently have added 3 forms, need add via "add form" button, think can using jquery append. how make work in google autocomplete?
thanks
your javascript code must more "generic" , not based on dom elements ids if want re-use manage multiple forms.
the global var containing autocomplete instance neitheir idea.
i edited jsfiddle suggest jquery based solution (you put jquery tag assume can rely on):
- i defined div
#addressforms
forms appended after cliking on#addform
button - i've wrapped form makup in hidden div
#template
. each time click on#addform
, template content copied, initialized autocomplete , appended#addressforms
- as dom elements ids must unique, removed form elements ids , use them css classes
- i removed global var
componentform
, added data (data-type
) on each field element
have in jsfiddle if feet needs.
edit:
i created jsfiddle accordingly comments. it's not finished yet can help.
Comments
Post a Comment