Address Autocomplete

0.0/5
<?php
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts');

function my_enqueue_scripts() {

    if(function_exists('is_checkout') && is_checkout()){
        // Insert your API key here
        $api_key = '';
        $url = "https://maps.googleapis.com/maps/api/js?key=$api_key&libraries=places";
        wp_enqueue_script( 'google-maps-js', $url );            
    }

}

function ple_hook_javascript() {
  ?>
  <script>
	//Optional, restrict the autocomplete to addresses from Auckland, New Zealand. 


	//Attach the autocomplete to the DOM element
	var billing_autocomplete = new google.maps.places.Autocomplete(jQuery('#billing_address_1')[0], {      
	});

	//Define what information we want back from the API
	billing_autocomplete.setFields(['address_components']);

	//Define a handler which fires when an address is chosen from the autocomplete
	billing_autocomplete.addListener('place_changed', function() {

  	var place = billing_autocomplete.getPlace();

  	if (place.address_components) {

      console.log(place.address_components)

      var street_number = place.address_components[0].short_name;
      var street_name = place.address_components[1].short_name
      var suburb = place.address_components[2].short_name;
      var city = place.address_components[3].short_name;
      var postcode = place.address_components[5].short_name;

      jQuery('#billing_address_1').val(street_name + ' ' + street_number);
      //jQuery('#billing_address_2').val(suburb);
      jQuery('#billing_city').val(city);
      jQuery('#billing_postcode').val(postcode);

  	}

	});
  </script>
  <?php
}

add_action( 'wp_footer', 'ple_hook_javascript' );

Comments and reviews

{{ reviewsTotal }} Review
{{ reviewsTotal }} Reviews
{{ options.labels.newReviewButton }}
{{ userData.canReview.message }}

Description

This snippet was fetched automatically from WPDistro.cz projects.

Author

Tags

This snippet is untagged