JSFiddle - React, Tailwind, and code Playground
by smombartz
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Geolocation Example</title>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDt7OcciflokvTrGkk_W9PyN73doIF6YE8&libraries=places" async defer></script>
</head>
<body>
<button id="getLocation">Get Location</button>
<form id="locationForm">
<input type="text" id="latlong" value="Latitude, Longitude">
<input type="text" id="city" value="City">
</form>
<div id="error"></div>
<script>
document.getElementById('getLocation').addEventListener('click', function() {
fetch('https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyDt7OcciflokvTrGkk_W9PyN73doIF6YE8', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({})
})
.then(response => response.json())
.then(data => {
if (data.location) {
const lat = data.location.lat;
const lng = data.location.lng;
document.getElementById('latlong').value = lat + ', ' + lng; // Update form input for latitude and longitude
const latlng = new google.maps.LatLng(lat, lng);
const geocoder = new google.maps.Geocoder();
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK && results[0]) {
let cityFound = false;
results[0].address_components.forEach((component) => {
if (component.types.includes('locality')) {
document.getElementById('city').value = component.long_name; // Update form input for city
cityFound = true;
}
});
if (!cityFound) {
results[0].address_components.forEach((component) => {
if (component.types.includes('administrative_area_level_1')...