Google Maps Javascript Api Get Latitude And Longitude By Address Example

Using Google Maps JavaScript API to Get Latitude and Longitude by Address

To get the latitude and longitude of an address using the Google Maps JavaScript API, you can follow these steps:

  1. Create an HTML page with a div element as the container for the map.
  2. Add the necessary JavaScript code to initialize the map and geocode the address.
  3. Display the latitude and longitude results.

Example:

Here is an example of how to use the Google Maps JavaScript API to get the latitude and longitude of an address:

    
      <!DOCTYPE html>
      <html>
      <head>
        <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY</script>
        <script>
        
        // Function to initialize the map and geocode the address
        function initMap() {
          var geocoder = new google.maps.Geocoder();
          var address = "1600 Amphitheatre Parkway, Mountain View, CA"; // Example address
          
          // Geocode the address
          geocoder.geocode({'address': address}, function(results, status) {
            if (status === 'OK') {
              var latitude = results[0].geometry.location.lat();
              var longitude = results[0].geometry.location.lng();
              
              // Display the latitude and longitude
              document.getElementById("result").innerHTML = "Latitude: " + latitude + "<br>Longitude: " + longitude;
              
              // Initialize the map
              var map = new google.maps.Map(document.getElementById("map"), {
                center: {lat: latitude, lng: longitude},
                zoom: 10
              });
              
              // Add a marker to the map
              var marker = new google.maps.Marker({
                position: {lat: latitude, lng: longitude},
                map: map,
                title: address
              });
            }
          });
        }
        
        </script>
      </head>
      <body>
        <div id="map" style="width: 100%; height: 400px;"></div>
        <div id="result"></div>
        
        <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
      </body>
      </html>
    
  

In this example, replace “YOUR_API_KEY” with your own Google Maps API key. The HTML page contains a

element with an id of “map” to display the map, and another

element with an id of “result” to display the latitude and longitude.

The JavaScript code initializes the map and geocodes the address. The latitude and longitude are extracted from the geocoding results, and the map is centered on those coordinates. Additionally, a marker is added to the map at the specified address location.

Same cateogry post

Leave a comment