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>
Please login or Register to submit your answer
Thanks for sharing, Rob!