Skip to content

Instantly share code, notes, and snippets.

@rochow
Last active February 3, 2022 10:36
Show Gist options
  • Save rochow/6fa122cdd152ca2ed00f to your computer and use it in GitHub Desktop.
Save rochow/6fa122cdd152ca2ed00f to your computer and use it in GitHub Desktop.
Gravity Forms - Get Longitude and Latitude of an Address
<?php
/*
The idea being a user enters their address, and on submission we grab the long & lat for the address
from Google and update 2 hidden inputs (which are most likely custom field inputs). You can then use
this data to plot pins on a map etc.
USAGE
add_action( "gform_pre_submission" , "mr_get_longlat_of_address"); // ALL FORMS
add_action( "gform_pre_submission_1" , "mr_get_longlat_of_address"); // SPECIFIC FORM (ID = 1 in exmaple)
$address = The user input(s) of their address. We can manually add specific location information if possible
to keep it accurate. "123 main st" could be anywhere. If entries are limited to a certain location we know
we can add that on the end safely.
$_POST["input_8"] = Name of the hidden input we're passing lng to
$_POST["input_7"] = Name of the hidden input we're passing lng to
*/
add_action( 'gform_pre_submission_1', 'mr_get_longlat_of_address' );
function mr_get_longlat_of_address( $form ){
$address = sanitize_text_field( $_POST['input_3'] ' '.$_POST['input_6'] );
$address .= ', Sydney, Australia';
$coordinates = file_get_contents( 'http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address) . '&sensor=true' );
if( $coordinates ) {
$coordinates = json_decode($coordinates);
$_POST['input_8'] = $coordinates->results[0]->geometry->location->lng;
$_POST['input_7'] = $coordinates->results[0]->geometry->location->lat;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment