I have the following code to prefill some other location-related fields:
/* ----------------------------------------------------------------------------
KevinSikora: auto fill location related fields when a user enters an address
*/
add_action( 'admin_enqueue_scripts', 'custom_enqueue_admin_scripts' );
function custom_enqueue_admin_scripts(){
wp_enqueue_script( 'location-fields', get_theme_file_uri( '/assets/js/location-fields.js' ), array( 'jquery' ), '2.5', true );
}
That references the following code in (themes->Newspaper-child->assets->js->location-fields.js):
( function( $ ) {
$( document ).ready( function(){
$("input.js-toolset-google-map").on( "geocode:result", function( event, result ){
var geometry = result.geometry;
$('input[name="wpcf[coordinates-latitude]"]').val(geometry.location.lat);
$('input[name="wpcf[coordinates-longitude]"]').val(geometry.location.lng);
var addressComponents = result.address_components;
var locality = "";
var administrative_area_level_1 = "";
var countryShort = "";
var country = "";
var location = ""; // contains concatenated location to be displayed
$.each( addressComponents, function( index, value ){
if ( addressComponents[ index ].types[0] == "locality" ) {
locality = addressComponents[ index ].long_name;
}
else if ( addressComponents[ index ].types[0] == "administrative_area_level_1" ) {
administrative_area_level_1 = addressComponents[ index ].long_name;
}
else if ( addressComponents[ index ].types[0] == "country" ) {
countryShort = addressComponents[ index ].short_name;
country = addressComponents[ index ].long_name;
}
} );
$('input[name="wpcf[locality]"]').val(locality);
$('input[name="wpcf[administrative_area_level_1]"]').val(administrative_area_level_1);
$('input[name="wpcf[country]"]').val(country);
location = country;
if((countryShort === "US") && administrative_area_level_1) {
location = administrative_area_level_1;
} // need to handle Canada, Australia with city, territory, country
if(locality) {
location = locality + ", " + location;
}
$('input[name="wpcf[location]"]').val(location);
} );
} );
})( jQuery );
The above code works fine except for the following two lines:
$('input[name="wpcf[coordinates-latitude]"]').val(geometry.location.lat);
$('input[name="wpcf[coordinates-longitude]"]').val(geometry.location.lng);
When the result comes back, should it have the (geometry) information? Or do I need to do something special to get that information?