Get Address From Latitude And Longitude Google Map Api Using Javascript

Get address from latitude and longitude using Google Maps API in JavaScript

To get the address from latitude and longitude using the Google Maps API, you can follow the steps outlined below:

  1. First, you need to include the Google Maps JavaScript API in your HTML document by adding the following script tag in the head section:
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
  1. Create a JavaScript function that takes latitude and longitude parameters:
function getAddressFromLatLng(lat, lng) {
  // Create a geocoder instance
  var geocoder = new google.maps.Geocoder();

  // Define the latlng object
  var latlng = new google.maps.LatLng(lat, lng);

  // Perform the reverse geocoding request
  geocoder.geocode({ 'latLng': latlng }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[0]) {
        // Get the formatted address
        var address = results[0].formatted_address;
        
        // Do something with the address
        console.log(address);
      } else {
        console.log('No results found');
      }
    } else {
      console.log('Geocoder failed due to: ' + status);
    }
  });
}

The function uses the Google Maps Geocoder service to get the address based on the provided latitude and longitude. It takes in the latitude and longitude as parameters, creates a geocoder instance, and performs a reverse geocoding request using the geocode() method. The resulting address is then logged to the console for demonstration purposes.

  1. Call the getAddressFromLatLng() function with the desired latitude and longitude values:
getAddressFromLatLng(37.7749, -122.4194);

In this example, the function is called with the latitude and longitude of San Francisco, CA. You can replace these values with your own coordinates to get the address for a different location.

Note: Make sure you replace YOUR_API_KEY in the Google Maps API script tag with your actual API key. You can obtain an API key by creating a project in the Google Cloud Console and enabling the Geocoding API.

Read more interesting post

Leave a comment