Get Geo Location Country, City Name, Zipcode from Latitude and Longitude in JavaScript

Get Geo Location Country, City Name, Zipcode from Latitude and Longitude in JavaScript

Sometimes, you need to geo location information like country name, state, city name, address, zipcode or postal code, street address, etc. So, you can use google geocoding API with javascript for that.

So, In this tutorial, you will learn how to get geo location information like country, city name, state name, zipcode, etc, from latitude and longitude in javascript using Google geocoding API without showing map.

How to Get Geo Location Country, State, City Name, Zipcode, Address from Latitude and Longitude in JavaScript

Using the below given steps, you can get geo location country, state, city name, address, zipcode, etc from latitude and longitude in javascript using Google geocoding API without google maps:

  • Step 1: Get API Key from Google Maps
  • Step 2: Set up your HTML
  • Step 3: Create Your JavaScript File (script.js)
  • Step 4: Testing

Step 1: Get API Key from Google Maps

You’ll need an API key from the Google Cloud Platform to use the Google Maps Geocoding API. You can create one by following these steps:

  • Go to the Google Cloud Platform Console: https://console.cloud.google.com/
  • Create a new project or select an existing one.
  • In the sidebar, navigate to “APIs & Services” > “Credentials.”
  • Click on “Create Credentials” and select “API Key.”
  • Copy the generated API key.

Step 2: Set up your HTML

Next, you need to create an HTML file with a form for inputting latitude and longitude. You’ll also need a div to display the result’s of geo location related information etc:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Reverse Geocoding Example</title>
</head>
<body>
    <h1>Reverse Geocoding</h1>
    <form id="location-form">
        <label for="latitude">Latitude:</label>
        <input type="text" id="latitude" placeholder="Enter latitude">
        <br>
        <label for="longitude">Longitude:</label>
        <input type="text" id="longitude" placeholder="Enter longitude">
        <br>
        <button type="submit">Get Location Info</button>
    </form>
    <div id="result">
        <!-- Display results here -->
    </div>
    <script src="script.js"></script>
</body>
</html>

Step 3: Create Your JavaScript File (script.js)

Once you have created HTML, Then you need to create script.js and add the following code to handle form submission and geocoding or geo location information:

document.addEventListener('DOMContentLoaded', () => {
    const form = document.getElementById('location-form');
    const latitudeInput = document.getElementById('latitude');
    const longitudeInput = document.getElementById('longitude');
    const resultDiv = document.getElementById('result');
    form.addEventListener('submit', (e) => {
        e.preventDefault();
        const latitude = parseFloat(latitudeInput.value);
        const longitude = parseFloat(longitudeInput.value);
        if (isNaN(latitude) || isNaN(longitude)) {
            alert('Please enter valid latitude and longitude.');
            return;
        }
        // Call the geocoding function
        getGeocodingData(latitude, longitude);
    });
    function getGeocodingData(latitude, longitude) {
        // Replace 'YOUR_API_KEY' with your actual API key if required
        const apiKey = 'YOUR_API_KEY';
        const apiUrl = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${apiKey}`;
        fetch(apiUrl)
            .then((response) => response.json())
            .then((data) => {
                const addressComponents = data.results[0].address_components;
                let countryName, cityName, stateName, zipcode;
                for (const component of addressComponents) {
                    if (component.types.includes('country')) {
                        countryName = component.long_name;
                    } else if (component.types.includes('locality')) {
                        cityName = component.long_name;
                    } else if (component.types.includes('administrative_area_level_1')) {
                        stateName = component.long_name;
                    } else if (component.types.includes('postal_code')) {
                        zipcode = component.long_name;
                    }
                }
                // Display the results
                resultDiv.innerHTML = `
                    <p>Country: ${countryName}</p>
                    <p>City: ${cityName}</p>
                    <p>State: ${stateName}</p>
                    <p>Zipcode: ${zipcode}</p>
                `;
            })
            .catch((error) => {
                console.error('Error fetching data:', error);
                resultDiv.innerHTML = '<p>Something went wrong. Please try again later.</p>';
            });
    }
});

Remember to replace ‘YOUR_API_KEY’ with your actual API key if required for the geocoding service you’re using.

Step 4: Testing

Open the HTML file in a web browser. Enter valid latitude and longitude coordinates in the form fields and click the “Get Location Info” button. The script will make an API request, and retrieve & display the country name, city name, state name, and zipcode based on the provided coordinates.

Conclusion

That’s it! You have learned how to extract location information like country, city name, zipcode, etc from latitude and longitude coordinates in javascript.

Recommended JavaScript Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *