Solving Geolocation Issue With Empty City Field

By: Rob LeVine | Asked: 11/15/2022
ForumsCategory: Code SnippetsSolving Geolocation Issue With Empty City Field
Rob LeVineRob LeVine asked 1 year ago
I had the occasion to need to extract just the City from the Formidable Geocoder object.  In 99% of the data, that's easy to do, by selecting the City field in the Geolocation options in the Formidable field.  However, because of this issue, for locales such as New York and Tokyo, the City ("locality" as Google Maps API calls it) is blank.  Fortunately, the "sublocality" contains information that's good enough (at least for me), e,g., instead of "Bronx", you can get at least get "New York".  I solved the issue by using jQuery to make the Google Maps API call to get the JSON data and stripping out the sublocality if the locality is not found.  I wrapped the following code in HTML script tags and put it in the After Fields section of the form with the geocoder.
jQuery(document).ready(function($) {
	"use strict";
	
	const pickupFieldKeyPrefix = "field_pickup";
	const API_KEY = "PUT YOUR GOOGLE MAPS SERVER API KEY HERE";

	const classPickupGeocoderLat = "frmgeo-geocoded-field-latitude";
	const classPickupGeocoderLng = "frmgeo-geocoded-field-longitude";

	const pickupCity = pickupFieldKeyPrefix + "_city";
	
	$("#" + pickupFieldKeyPrefix + "_location").change(function() {
		var latPickup = $("#" + pickupFieldKeyPrefix + "_geocoder." + classPickupGeocoderLat).val();
		var lngPickup = $("#" + pickupFieldKeyPrefix + "_geocoder." + classPickupGeocoderLng).val();
		getCity(latPickup, lngPickup, pickupCity);
	});

	function getCity(lat, lng, cityField) {
		var latlng = lat + "," + lng;
		$.ajax({
			type: "GET",
			url: "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latlng + "&sensor=false&key=" + API_KEY,
			dataType: "json"
		}).success(function(data){
			processJSON(data, cityField);
		});
	}
	
	function processJSON(data, cityField) {
		var city = null;
		var locality = null;
		var sublocality = null;
		
		/* look for city (locality) and find sublocality just in case */
		for (var i=0;i<data.results.length;i++) {
			var types = data.results[i].types;
			for (var j=0;j<types.length;j++) {
				if (types[j] == "locality") {
					locality = data.results[i].address_components[0].long_name;
				}
				if (types[j] == "sublocality") {
					sublocality = data.results[i].address_components[0].long_name;
				}
			}
		}
		
		city = (locality) ? locality : sublocality;
		
		if (!$("#"+cityField).val()) {
			$("#"+cityField).val(city);
		}
	}
});
/pre>
Bobby Clapp replied 1 year ago

Thanks for sharing, Rob!

Making the Best WordPress Plugin even better - Together

Take on bigger projects with confidence knowing you have access to an entire community of Formidable Experts and Professionals who have your back when the going gets tough. You got this!
Join the community
crossarrow-right