Last active
February 27, 2018 19:10
-
-
Save davidsword/7267840fabb5b911aa9a7c524a9d85f8 to your computer and use it in GitHub Desktop.
A simple script to get the geo coordinates of a location via Google Map API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<input type="text" name="location_meta[address]" placeholder="Street Address" value=""> | |
<input type="text" name="location_meta[city]" placeholder="City" value="">, | |
<input type="text" name="location_meta[prov]" placeholder="State/Prov" value="">, | |
<select name="location_meta[country]"> | |
<option value='CA'>🇨🇦</option> | |
<option value='US'>🇺🇸</option> | |
</select><br> | |
<input type="text" name="location_meta[postal]" placeholder="Postal/Zip" value=""> | |
<button data-get-geo-cords>Click here to get Lat/Lng from address above</button> | |
<input type="text" id="lat" class="code" name="location_meta[lat]" placeholder="Latitude"> | |
<input type="text" id="lng" class="code" name="location_meta[lng]" placeholder="Longitude"> | |
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE"></script> | |
<script> | |
const geoCordsAction = document.querySelector('[data-get-geo-cords]'); | |
geoCordsAction.addEventListener('click', (e) => { | |
e.preventDefault(); | |
geocoder = new google.maps.Geocoder(); | |
const address = document.querySelector("[name='location_meta[address]']").value; | |
const city = document.querySelector("[name='location_meta[city]']").value; | |
const prov = document.querySelector("[name='location_meta[prov]']").value; | |
const country = document.querySelector("[name='location_meta[country]']").value; | |
const postal = document.querySelector("[name='location_meta[postal]']").value; | |
const fullAddress = `${address}, ${city} ${prov}, ${country}, ${postal}`; | |
geocoder.geocode( { | |
address: address, | |
componentRestrictions: { | |
country : country | |
} | |
}, function(results, status) { | |
if (status == google.maps.GeocoderStatus.OK) { | |
document.querySelector("#lat").value = results[0].geometry.location.lat(); | |
document.querySelector("#lng").value = results[0].geometry.location.lng(); | |
} else { | |
console.info(google.maps.GeocoderStatus); | |
} | |
}); | |
return false; | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment