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

[ad_1]

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

How to Get Country, City Name, Zipcode from Latitude and Longitude in JavaScript

Steps to get country, city name, zipcode, and location from latitude and longitude in javascript using Google geocoding API:

  • 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 results:

<!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:

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

[ad_2]

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00