Google Maps API: Integration Guide and Basic Functions

Google Maps is the dominant global location platform, widely used by a vast audience. Given its ubiquitous presence, e-commerce businesses have a valuable opportunity to elevate the online shopping experience by seamlessly incorporating Google Maps API into their Magento 2 websites.

In this blog, we’ll show you how to implement Google Maps to CMS pages in Magento and introduce some basic functions for leveraging the Google Maps API.

What is Google Maps API?

The Google Maps API, or Google Maps Application Programming Interface, is a set of web services and tools provided by Google to enable developers to integrate Google Maps functionality into their applications, websites, and services.

It allows developers to access various mapping and geolocation features, including displaying maps, adding markers, obtaining directions and routes, geocoding (converting addresses into geographic coordinates), and more.

Google Maps API

Google Maps Platform offers multiple APIs for different aspects of its service:

  • Maps Static API: This API allows for embedding static Google Maps images into applications and websites. It’s useful for scenarios where you need a simple, non-interactive map display.
  • Maps JavaScript API: the Maps JavaScript API is one of the most versatile and widely used. It enables developers to create interactive and highly customizable maps with various features and functionalities, such as markers, overlays, and geolocation.
  • Places API: the Places API provides access to a vast database of points of interest (POIs) and location data. Developers can use this API to search for places, retrieve details about specific locations, and integrate place information into their applications.
  • Directions API: the Directions API is essential for applications that require route planning and navigation. It offers features like calculating directions between two or more locations, estimating travel time, and providing step-by-step route guidance.

Google Maps has a ‘pay-as-you-use’ pricing structure for its platform API. This updated model offers increased flexibility and autonomy to developers utilizing Google Maps APIs. The pricing for Google Maps Platform APIs can be adjusted to suit your requirements without requiring commitments, termination fees, or usage restrictions.

Benefits of Google Maps API Integration

Integrating Google Maps API into your Magento 2 website offers a range of benefits, especially for e-commerce businesses. Here are some of the outstanding advantages that may be compelling for you.

Enhanced User Experience

Google Maps offers interactive maps that help customers locate physical stores, distribution centers, or pickup points easily. This convenience enhances the overall shopping experience and encourages customers to make purchases.

Location-Based Services

You can provide customers with location-based services, such as showing the nearest stores, stock availability in local branches, and personalized promotions based on a customer’s location.

Distance Calculations

With this advantage, e-businesses can calculate distances between two points, which can be valuable for providing shipping cost estimates.

Optimized Routes

For businesses involved in delivery services, integrating Google Maps API can help optimize routes for your delivery personnel, reducing delivery times and fuel costs.

How to get Google Maps API and add it to the CMS Page of the Magento 2 website

You can seamlessly integrate Google Maps API into your Magento 2 website by following the steps below.

1. Obtain a Google Maps API Key

To get started, you need a Google Maps API key. This key acts as your authorization to access Google’s mapping services. You can obtain one by creating a project in the Google Cloud Console.

2. Enable the API

Within your Google Cloud Console, enable the specific APIs you need, such as the Geocoding API, Maps JavaScript API, or Places API. Make sure to set up the API restrictions and usage limits to control access.

3. Magento Configuration

  • In your Magento 2 admin panel, navigate to the configuration settings.
  • Locate the Google API section and paste your API key.
  • Go to Stores ⇒ Configuration ⇒ General ⇒ Content Management

4. Show Google Maps by using static content

  • You can display Google Maps by using a static block or CMS Page.
  • Go to Content ⇒ CMS Page ⇒ Create your CMS Page
Google Maps API backend

5. Result

With just a few simple clicks, you can easily create a CMS page that resembles the appearance of Google Maps, as shown in the images below.

Google Maps API in CMS Page
Google Maps API in CMS Page

3 basic functions from Google Maps API

If you want more advanced integration, you will need to do some coding. Below, this article will share three basic functions to support the features of the Google API.

Get the Address by latitude and longitude

If you need to retrieve addresses based on latitude and longitude coordinates, you can create a custom block using the provided code. This block allows you to fetch addresses as needed.

<?php

namespace Vendor\Module\Block;

use Magento\Framework\View\Element\Template;
use Magento\PageBuilder\Block\GoogleMapsApi;
use Magento\Framework\HTTP\ClientInterface;
use Magento\Framework\Serialize\Serializer\Json;


class CustomBlock extends Template
{
    protected $googleApi;
  private $client;
  private $json;


    public function __construct(
        GoogleMapsApi $googleApi,
    ClientInterface $client,
    Json $json,
        Template\Context $context,
        array $data = []
    ) {
        	$this->googleApi = $googleApi;
$this->client = $client;
        	$this->json = $json;
parent::__construct($context, $data);
    }

  public function getAddress($lat, $lng)
    {
       	$api_key = $this->googleApi->getApiKey();
        $url = "https://maps.googleapis.com/maps/api/geocode/json";

        $queryString = http_build_query([
                        'key' => $googleApiKey,
                        'latlng' => "{$lat},{$lat}"
                    ]);

        $this->client->get($url . '?' . $queryString);
        return $this->json->unserialize($this->client->getBody());
    }


}

Google Distance Matrix API

For applications requiring distance calculations and route optimization, the Google Distance Matrix API is invaluable. The provided code can calculate distances between two locations and retrieve distance information.

<?php

namespace Vendor\Module\Block;

use Magento\Framework\View\Element\Template;
use Magento\PageBuilder\Block\GoogleMapsApi;
use Magento\Framework\HTTP\ClientInterface;
use Magento\Framework\Serialize\Serializer\Json;


class CustomBlock extends Template
{
    protected $googleApi;
  private $client;
  private $json;


    public function __construct(
        GoogleMapsApi $googleApi,
    ClientInterface $client,
    Json $json,
        Template\Context $context,
        array $data = []
    ) {
        	$this->googleApi = $googleApi;
$this->client = $client;
        	$this->json = $json;
parent::__construct($context, $data);
    }

  public function getAddress($oLat, $olng, $dLat, $dlng)
    {
        $api_key = $this->googleApi->getApiKey();
        $url = "https://maps.googleapis.com/maps/api/distancematrix/json";

        $queryString = http_build_query([
                        'key' => $api_key,
                        'origins' => "{$oLat},{$olng}",
                        'destinations' => "{$dLat},{$dlng}",
                        'mode' => 'driving',
                    ]);


        $this->client->get($url . '?' . $queryString);
        return $this->json->unserialize($this->client->getBody());
    }


}

Get latitude and longitude

To obtain latitude and longitude coordinates from an address, create a custom block using the code snippet. This block allows you to convert addresses into geographic coordinates for further use in your e-commerce website.

<?php

namespace Vendor\Module\Block;

use Magento\Framework\View\Element\Template;
use Magento\PageBuilder\Block\GoogleMapsApi;
use Magento\Framework\HTTP\ClientInterface;
use Magento\Framework\Serialize\Serializer\Json;


class CustomBlock extends Template
{
    protected $googleApi;
  private $client;
  private $json;


    public function __construct(
        GoogleMapsApi $googleApi,
    ClientInterface $client,
    Json $json,
        Template\Context $context,
        array $data = []
    ) {
        	$this->googleApi = $googleApi;
$this->client = $client;
        	$this->json = $json;
parent::__construct($context, $data);
    }

  public function getAddress($address)
    {
	 // Example: $address = '1600 Amphitheatre Parkway, Mountain View, CA';

        $api_key = $this->googleApi->getApiKey();
        $url = "https://maps.googleapis.com/maps/api/geocode/json";

        $queryString = http_build_query([
                        'key' => $api_key,
                        'address' => "{$address}"
                    ]);


        $this->client->get($url . '?' . $queryString);
        return $this->json->unserialize($this->client->getBody());
    }


}

In conclusion

The integration of Google Maps API into your Magento 2 website offers a myriad of advantages for e-commerce businesses. With the step-by-step guide provided in this blog, you can seamlessly implement Google Maps API and improve customers’ shopping experience. To understand how Tigren applies the Google Maps API to a specific case, stay tuned for our upcoming blog.

Moreover, in addition to the benefits of Google Maps API integration, you can further enhance your e-commerce website by incorporating additional extensions. At Tigren, we offer many free extensions that can create a more user-friendly, efficient, and customer-centric shopping experience. Don’t hesitate to explore these extensions and discover how they can amplify your e-commerce capabilities.

Affordable-Magento-development-services-Website-PWA-Hybrid-App-Extensions

Leave a Reply

Your email address will not be published. Required fields are marked *