How to convert a text address into geographic coordinates using Google's Geocoding API

How to convert a text address into geographic coordinates using Google's Geocoding API

The process of converting a real text address to geographic coordinates, for example ("Plaza de Bolívar de Bogotá") into geographic coordinates (like latitude 4.5981206 and longitude -74.0760435), is called Geocoding, you may store this information in your database to place markers on Google maps or any other thing you may imagine. The geocoding API of google provides a pretty easy way to access these services via an HTTP request. The only disadvantage with this Google API is that isn't available in the free tier, so you will have to pay for every request (0.005 USD or 5 USD per 1000 requests).

In this article, I will explain to you how to easily obtain the coordinates from a real text address with the Geocoding API of Google.

1. Enable Geocoding API

The first thing you need to do is to enable access to the Geocoding API in the Google Cloud Platform. Open the console and head to the API Library zone or the marketplace here. Then, search for the Geocoding API:

Geocoding API Google Cloud Platform

And enable it:

Enable Google Cloud Geocoding API

Remember that for the use of Geocoding, you will be charged either for the plain Geocoding API or the Maps JavaScript API’s Geocoding service, 0.005 USD per request or 5 USD per 1000 requests.

2. Using the Geocoding API in Google Maps

If you are working in the frontend, you may simply include the Google Maps API file in your document, just be sure to replace <YOUR-GOOGLE-MAPS-PLATFORM-API-KEY> with your own Google Maps Platform API Key:

<script src="https://maps.googleapis.com/maps/api/js?key=<YOUR-GOOGLE-MAPS-PLATFORM-API-KEY>" async></script>

And use the geocoder with the following logic:

// 1. Initialize GeoCoder
const geocoder = new google.maps.Geocoder();

// 2. The text address that you want to convert to coordinates
let address = "Plaza de Bolívar de Bogotá";

// 3. Obtain coordinates from the API
geocoder.geocode({ address: address }, (results, status) => {
    if (status === "OK") {
        // Display response in the console
        console.log(results);
    } else {
        alert("Geocode error: " + status);
    }
});

The response in this case with the given address in Colombia would be the following object, where you will find the coordinates of the location (lat 4.5981206, lng -74.0760435):

[
    {
        "address_components": [
            {
                "long_name": "11-10",
                "short_name": "11-10",
                "types": [
                    "street_number"
                ]
            },
            {
                "long_name": "Carrera 7",
                "short_name": "Cra. 7",
                "types": [
                    "route"
                ]
            },
            {
                "long_name": "La Catedral",
                "short_name": "La Catedral",
                "types": [
                    "neighborhood",
                    "political"
                ]
            },
            {
                "long_name": "La Candelaria",
                "short_name": "La Candelaria",
                "types": [
                    "political",
                    "sublocality",
                    "sublocality_level_1"
                ]
            },
            {
                "long_name": "Bogotá",
                "short_name": "Bogotá",
                "types": [
                    "locality",
                    "political"
                ]
            },
            {
                "long_name": "Bogotá",
                "short_name": "Bogotá",
                "types": [
                    "administrative_area_level_1",
                    "political"
                ]
            },
            {
                "long_name": "Colombia",
                "short_name": "CO",
                "types": [
                    "country",
                    "political"
                ]
            },
            {
                "long_name": "111711",
                "short_name": "111711",
                "types": [
                    "postal_code"
                ]
            }
        ],
        "formatted_address": "Cra. 7 #11-10, La Candelaria, Bogotá, Colombia",
        "geometry": {
            "location": {
                "lat": 4.5981206,
                "lng": -74.0760435
            },
            "location_type": "ROOFTOP",
            "viewport": {
                "south": 4.596771619708497,
                "west": -74.07739248029151,
                "north": 4.599469580291502,
                "east": -74.0746945197085
            }
        },
        "place_id": "ChIJj-XP7KeZP44RdhQ1NSu3nAk",
        "plus_code": {
            "global_code": "67P7HWXF+6H"
        },
        "types": [
            "establishment",
            "point_of_interest",
            "tourist_attraction"
        ]
    }
]

Is most likely that you will display the obtained coordinates in the Google Maps element in the document. The following document shows a very basic example of a search box, where the user is able to type the text address, so when the API converts it to geolocation object, it will be shown on the map:

<!DOCTYPE html>
<html>
    <head>
        <title>Geocoding Service</title> 
    </head>
    <body>
        <!-- 1. Create a searchbox where the user will provide the text address -->
        <div id="floating-panel">
            <input id="address" type="textbox" value="Sydney, NSW" />
            <input id="submit-btn" type="button" value="Geocode" />
        </div>

        <div id="map" style="height: 500px;"></div>

        <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
        <script src="https://maps.googleapis.com/maps/api/js?key=<YOUR-GOOGLE-MAPS-PLATFORM-API-KEY>&callback=initMap" async></script>

        <script>
            // 1. Initialize a basic map
            function initMap() {
                const map = new google.maps.Map(document.getElementById("map"), {
                    zoom: 8,
                    center: {
                        lat: -34.397,
                        lng: 150.644
                    }
                });

                // 2. Initialize the GeoCoder API
                const geocoder = new google.maps.Geocoder();

                // 3. So when the user clicks on the submit BTN, geocode the given address if possible
                document.getElementById("submit-btn").addEventListener("click", () => {
                    geocodeAddress(geocoder, map);
                });
            }

            // Handle conversion of text address to coordinates
            function geocodeAddress(geocoder, resultsMap) {
                const address = document.getElementById("address").value;

                // Search for the address with the API
                geocoder.geocode({ address: address }, (results, status) => {
                    if (status === "OK") {
                        // Display response in the console
                        console.log(results);

                        // Set the location of the map obtained by the API
                        resultsMap.setCenter(results[0].geometry.location);

                        // Add the marker with the obtained location
                        new google.maps.Marker({
                            map: resultsMap,
                            position: results[0].geometry.location,
                        });
                    } else {
                        alert("Geocode error: " + status);
                    }
                });
            }
        </script>
    </body>
</html>

3. Using the plain Geocoding API

If you want to use the API without using Google Maps in the browser, for example, in the backend using PHP, Node.js, or Go, you will need to proceed differently. There's an endpoint where you need to request the information, providing 2 GET parameters:

  • address: contains the URL encoded string of the address that you want to convert into coordinates with the API
  • key: the Google Maps Platforms API Key. 
https://maps.googleapis.com/maps/api/geocode/json?address=<URL-ENCODED-TEXT-ADDRESS>&key=<YOUR-API-KEY>

For example, with a language like PHP, you could use a cURL based library to send the request to the backend or make it even simpler with file_get_contents:

<?php

// 1. Encode the Address to be safely placed inside a URL
$address = urlencode("Bucaramanga, Colombia");
// 2. Your Google Maps Platform APIKey
$apikey = "your-api-key";

// 3. Request the geocoding from the given address
$response = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=$apikey");

// 4. Output JSON with response
echo $response;

Whose output would be the following JSON:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Bucaramanga",
               "short_name" : "Bucaramanga",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Bucaramanga",
               "short_name" : "Bucaramanga",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Santander",
               "short_name" : "Santander",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "Colombia",
               "short_name" : "CO",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Bucaramanga, Santander, Colombia",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 7.166567,
                  "lng" : -73.09386590000001
               },
               "southwest" : {
                  "lat" : 7.071845,
                  "lng" : -73.17209009999999
               }
            },
            "location" : {
               "lat" : 7.119349,
               "lng" : -73.1227416
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 7.166567,
                  "lng" : -73.09386590000001
               },
               "southwest" : {
                  "lat" : 7.071845,
                  "lng" : -73.17209009999999
               }
            }
         },
         "place_id" : "ChIJ7cBR93oVaI4RbMNIEVXkoHU",
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

And so easily can we convert any text address like "123 Fake Street" to coordinates that we can place in any Google Maps.

Happy coding ❤️!

References and external resources

This could interest you

Become a more social person