JavaScript API Tutorials

Here is a New Way To Search Within Google Maps with Geocoding API

Internet users across the world rely on Google Maps for everyday traffic navigation as well as searching for interesting places. You key in the address of the place and it pops out a balloon pinned to the location on the map. This is known as geocoding (getting lat long from an address). But what if you suddenly get dropped somewhere in the middle of an unknown city? The first thing you want to find out is the address of your current location. This is known as reverse geocoding.

With the help of Google Maps Geocoding API, you can easily achieve both. Moreover, you can also leverage this API with the Google Maps SDK to build an address hunting feature on Google Maps. Want to know how? Then follow along this blog post to see how we build a simple web app to experience Google Maps in a different way.

Connect to the Google Maps Geocoding API

How to Get Access to the Google Maps Geocoding API?

Google Maps Geocoding API provides the endpoints for performing geocoding as well as reverse geocoding. To build the web app with Google Maps Geocoding API on RapidAPI, follow the steps below to activate the API with your RapidAPI account.

1. Sign Up for RapidAPI Account

To begin using the Google Maps Geocoding API, you’ll first need to sign up for a free RapidAPI developer account. With this account, you get a universal API Key to access all APIs hosted on RapidAPI.

RapidAPI is the world’s largest API marketplace, with over 10,000 APIs and a community of over 1,000,000 developers. Our goal is to help developers find and connect to APIs to help them build amazing apps.

2. Subscribe to Google Maps Geocoding API

Once signed in, log in to your RapidAPI account and access the API console.

Now click on the “Pricing” tab and opt-in for the basic subscription that gives you 500 free API calls to Google Maps Geocoding API per month.

How much does the Google Geocoding API cost?

The API has 3 pricing tiers depending on your usage as seen in the image above:

  1. Basic – $0/month – 500 API calls/month – $0.01/call for overages
  2. Pro – $5/month – 1,000 API calls/month – $0.005/call for overages
  3. Ultra – $400/month – 100,000 API calls/month – $0.004/call for overages

Is the Google Geocoding API free?

While the API isn’t completely free, it does offer a Basic freemium plan that allows developers to use the API up to 500 times/month. After 500 calls, you will be charged $0.01 per call.

3. Test Your API Subscription

Once you are subscribed, come back to the “Endpoints” tab. Here is a closer look at the two endpoints.

Select the “GET Reverse Geocoding” endpoint and hit the “Test Endpoint” button with the default parameters.

You will notice that the API performs a reverse geocoding of the location coordinates passed in the ‘latlng’ parameter. In this case, the coordinates “40.714224,-73.96145” are converted to an address in New York, USA.

The API also returns each address component as part of the JSON array.

If you got the same API response along with HTTP status code 200, then you are good to go. In the next section, we will look at leveraging this endpoint to build a web app on Google Maps.

Connect to the Google Maps Geocoding API

Address Hunting on Google Maps

So what is address hunting?

Whenever you search for a building on Google Maps, you are almost always sure about the name and address of the building. But, what if you are in a situation when you do not know the name. You probably just recall the name of the street or the road, or maybe a nearby landmark.

Using the reverse geocoding feature of Google Maps Geocoding API, you can get the address of a location coordinate as long as you hunt down the landmark icons and labels on the Google Maps with mouse clicks. That’s exactly what we are going to do with the address hunting web app.

Follow the steps below to build a demo HTML page that loads Google Maps with the address hunting feature, powered by Google Maps Geocoding API.

How to use the Google Maps Geocoding API with JavaScript

1. Create The Static HTML

We start with the boilerplate Google Maps HTML page. The UI contains a single <div> element to hold the Google Maps instance and we add some CSS to extend it across the entire viewport.

<!DOCTYPE html>
<html>
  <head>
    <title>Address Hunting</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      
      #map {
        height: 100%;
      }
      
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=<YOUR_GOOGLEMAPS_APIKEY>&callback=initMap">
    </script>
    <script
    src="https://code.jquery.com/jquery-3.4.1.min.js"
    integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
    crossorigin="anonymous"></script>
  </body>
</html>

You must replace the placeholder <YOUR_GOOGLEMAPS_APIKEY> with your own API key for Google Maps JavaScript API, obtained from the Google Cloud Platform console.

Note: Google has recently changed the way you get an API key for Google Maps. If you have an older API key for Google Maps, you will have to migrate that to a new billing account under the Google Cloud Platform. Otherwise, you have to set up a new Billing account. You can still use your older key without the billing account but Google Maps will display an overlay text “For development purposes only” upon rendering the map.

Connect to the Google Maps Geocoding API

2. Initialize the Map and Set Default Zoom and Position

With the HTML in place, you can now initialize the Google Maps Javascript SDK to load the map.

Define a new <script> block inside <body> , after the <div id="map"></div> declaration.

<script>

      var map, infoWindow;

      function initMap() {
        
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 6
        });

        infoWindow = new google.maps.InfoWindow;

        if (navigator.geolocation) {

          navigator.geolocation.getCurrentPosition(function(position) {

            let pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
            
            infoWindow.open(map);
            map.setCenter(pos);

          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });

        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }
      }

      function handleLocationError(browserHasGeolocation, infoWindow, pos)         {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
                              'Error: The Geolocation service failed.' :
                              'Error: Your browser doesn't support geolocation.');
        infoWindow.open(map);
      }

</script>

This code initializes the Google Maps JavaScript SDK. It sets the map position to your device position, detected from the HTML5 geolocation API, and sets the zoom level to 6.

3. Add Reverse Geocoding Capability To Display Address on Mouse Click

With the Google Maps initialized, it’s time to enable address hunting. We will use the mouse click on the Google Maps UI as a means to trigger the Google Maps Geocoding API and display the address.

For this, we have to first capture the location coordinates at the point of mouse click and then pass the latitude and longitude value of that coordinate to the Google Maps Geocoding API. The address returned from the API response is displayed via the google.maps.InfoWindow object which we have already initialized.

Here is the code for handling the mouse click inside Google Maps. You can add it after the infoWindow = new google.maps.InfoWindow; statement.

google.maps.event.addListener(map, 'click', function( event ){

          let latitude = event.latLng.lat();
          let longitude = event.latLng.lng();

          let pos = {

            lat : latitude,
            lng : longitude

          };

          settings.url = "https://google-maps-geocoding.p.rapidapi.com/geocode/json?language=en&latlng=" + latitude + "," + longitude;

          $.ajax(settings).done(function (response) {
              console.log(response);
            
              if(response.results.length > 0){
                infoWindow.setContent(response.results[0].formatted_address);  
              } else {
                infoWindow.setContent("Address Not Found");  
              }

              infoWindow.setPosition(pos);
              infoWindow.open(map);
              
    });

});

You can notice that we have an AJAX call inside the event handler to invoke the Google Maps Geocoding API. The settings for the AJAX call have to be defined as a separate variable at the beginning of the <script> block as follows.

var settings = {
        "async": true,
        "crossDomain": true,
        "method": "GET",
        "headers": {
          "x-rapidapi-host": "google-maps-geocoding.p.rapidapi.com",
          "x-rapidapi-key": “<YOUR_RAPIDAPI_KEY>"
    }
}

This settings variable contains the AJAX parameters including the API headers. Here you have to replace the placeholder <YOUR_RAPID_API> with your RapidAPI subscription key.

We are now done with the code.

The Final Showdown

Here is the complete code in case you want to copy and paste it in one shot.

<!DOCTYPE html>
<html>
  <head>
    <title>Address Hunting</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      
      #map {
        height: 100%;
      }
      
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>

      var settings = {
        "async": true,
        "crossDomain": true,
        "method": "GET",
        "headers": {
          "x-rapidapi-host": "google-maps-geocoding.p.rapidapi.com",
          "x-rapidapi-key": "<YOUR_RAPIDAPI_KEY>"
        }
      }

      var map, infoWindow;

      function initMap() {
        
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 6
        });

        infoWindow = new google.maps.InfoWindow;

        google.maps.event.addListener(map, 'click', function( event ){

          let latitude = event.latLng.lat();
          let longitude = event.latLng.lng();

          let pos = {

            lat : latitude,
            lng : longitude

          };

          settings.url = "https://google-maps-geocoding.p.rapidapi.com/geocode/json?language=en&latlng=" + latitude + "," + longitude;

          $.ajax(settings).done(function (response) {
              console.log(response);
            
              if(response.results.length > 0){
                infoWindow.setContent(response.results[0].formatted_address);  
              } else {
                infoWindow.setContent("Address Not Found");  
              }

              infoWindow.setPosition(pos);
              infoWindow.open(map);
              
            });

        });

        // Try HTML5 geolocation.
        if (navigator.geolocation) {

          navigator.geolocation.getCurrentPosition(function(position) {

            let pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
            
            infoWindow.open(map);
            map.setCenter(pos);

          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });

        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }
      }

      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
                              'Error: The Geolocation service failed.' :
                              'Error: Your browser doesn't support geolocation.');
        infoWindow.open(map);
      }

    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=<YOUR_GOOGLEMAPS_APIKEY>&callback=initMap">
    </script>
    <script
    src="https://code.jquery.com/jquery-3.4.1.min.js"
    integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
    crossorigin="anonymous"></script>
  </body>
</html>

Copy this code in a code editor, replace the placeholders with your RapidAPI and Google Maps subscription keys and save it as a .html file.

Launch this HTML file on the browser. You will be prompted by the browser for your consent to allow location sharing on this HTML page.

Once you do that, Google Maps will load and will be centered around your position. Click anywhere on the map and you should see a popup displaying the address of the location where you clicked.

And that’s it for this API tutorial.

Connect to the Google Maps Geocoding API
I hope you had good fun building this web app with Google Maps Geocoding API and Google Maps Javascript SDK. Go ahead and see if you can explore and find some really good use cases for address hunting on Google Maps. We can’t wait to see it working in a real-world app.

Related: How to use Google Maps API in React

5/5 - (1 vote)
Share
Published by

Recent Posts

Power Up Your Enterprise Hub: New March Release Boosts Admin Capabilities and Streamlines Integrations

We're thrilled to announce the latest update to the Rapid Enterprise API Hub (version 2024.3)!…

2 weeks ago

Unveiling User Intent: How Search Term Insights Can Empower Your Enterprise API Hub

Are you curious about what your API consumers are searching for? Is your Hub effectively…

2 weeks ago

Rapid Enterprise API Hub Levels Up Custom Branding, Monetization, and Management in February Release

The RapidAPI team is excited to announce the February 2024 update (version 2024.2) for the…

1 month ago

Supercharge Your Enterprise Hub with January’s Release: Search Insights, Login Flexibility, and More!

This January's release brings exciting features and improvements designed to empower you and your developers.…

3 months ago

Enhanced Functionality and Improved User Experience with the Rapid API Enterprise Hub November 2023 Release

Rapid API is committed to providing its users with the best possible experience, and the…

5 months ago

The Power of Supporting Multiple API Gateways in an API Marketplace Platform

In today's fast-paced digital world, APIs (Application Programming Interfaces) have become the backbone of modern…

6 months ago