Implement AJAX in order to circumvent fees from Google Maps and display maps exclusively upon user interaction by clicking a designated button

Starting July 16, 2018, the Google Maps API is no longer completely free.

After July 16, 2018, in order to continue utilizing the Google Maps Platform APIs, you must activate billing for each of your projects.
(https://developers.google.com/maps/documentation/javascript/usage-and-billing).

Since implementing the new Google Maps API along with the required key and billing information a week ago, I have noticed significant charges for my usage. This indicates high traffic to my website, which is positive. However, the issue arises from the fact that most of my visitors may not necessarily view or interact with the maps all the time, yet I am charged as soon as a page containing a map loads.

My solution involves not displaying the map by default, but instead providing a "Show map" link so that only users who are genuinely interested can view it. I intend to make an AJAX call to the Google Maps API when necessary. While I acknowledge that this approach may seem like a way to avoid charges, I believe it is fair as I only wish to be billed when visitors actively engage with the Google Maps feature and not just when pages load. Would Google consider this approach acceptable or view it as cheating? Refer to the code at https://developers.google.com/maps/documentation/javascript/tutorial. The plan is to trigger this code block via an AJAX request when users click a "Show map" button in order to reduce costs:

<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script>

UPDATE 1: In light of reading Executing <script> inside <div> retrieved by AJAX, particularly the response by Chocula:

JavaScript added as DOM text will not execute.

Considering this, attempting the method I have described may not be successful, as JavaScript inserted as DOM text does not run. While it seems like a clever way to avoid charges in cases where users do not interact with the map, it may not work in this scenario with AJAX. Inserting the <script>...</script> block through AJAX would result in it not executing, thus potentially invalidating the strategy. Immediate billing would occur regardless of whether the map is displayed by showing the <div id="map"></div> section. While it is an intriguing method to bypass payments fairly, I have doubts about its feasibility with AJAX.

Answer №1

One approach you could consider is utilizing a placeholder image that hints at a map, loading the Javascript without triggering the map functions (typically initiated through initMap in Google's examples)

The example provided below may be exaggerated, but it conveys the concept I am proposing. By monitoring the map loads using the Google console, I noticed that simply loading the page did not increase the counter. However, once the map was interacted with and properly invoked, the quota counter showed an increment.

This method could prove to be beneficial...

<!DOCTYPE html>
<html lang='en'>
  <head>
    <meta charset='utf-8' />
    <title>Load a map on demand</title>
    <style>
        html, body {
            height:100vh;
            width:100%;
            margin: 0;
            padding: 0;
        }
        body{
            display:flex;
            align-items:center;
            justify-content:center;
            background:whitesmoke;
        }
        #map {
            height:90vh;
            width:90%;
            margin:auto;
            border:3px solid rgba(0,0,0,1);
        }
        .staticmap{
            background-image:url(/images/maps/static-map-scotland.jpg);
            background-position:top left;
            background-size:cover;
            display:flex;
            align-items:center;
            justify-content:center;
            border:3px solid rgba(0,0,0,0.25)!important;
        }
        /* utilize a pseudo element class to show a message */
        .staticmap:after{
            content:attr(data-info);
            font-size:3rem;
            color:red;
            width:100%;
            display:block;
            text-align:center;
        }
    </style>
    <script>
        document.addEventListener('DOMContentLoaded',function(){

            let map=document.getElementById('map');

            const initMap=function() {
                var default_location = {
                    lat:56.646577,
                    lng:-2.888609
                };
                map = new google.maps.Map( map, {
                    zoom: 10, 
                    center: default_location,
                    mapTypeId:'roadmap',
                    mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU }
                });
                let options={
                    position:default_location,
                    map:map,
                    icon:'//maps.google.com/mapfiles/ms/icons/blue-pushpin.png',
                    title:'Default location'
                }

                marker = new google.maps.Marker( options );
            }


            /* inform the user to click the map to access its functionalities */
            map.onmouseover=function(){ 
                this.dataset.info='Click on the map to load';
            };
            map.onmouseout=function(){
                this.dataset.info='';
            };

            document.querySelector('.staticmap').onclick=function(){
                if( confirm('Would you like to load the proper map?') ){

                    /* fully invoke the map */
                    initMap();

                    /* remove the class that displayed the static image */
                    this.classList.remove('staticmap');
                }
            }
        },false);
    </script>






    <!--
        Instead of running the map initialization as a callback (using the querystring parameter `callback=initMap`)
        or in-line as a page load function (e.g., `onload=initMap`), refrain from any execution at this stage.
    -->
    <script async defer src="//maps.googleapis.com/maps/api/js?key=APIKEY"></script>


  </head>
  <body>
    <div id='map' class='staticmap' data-info=''></div>
  </body>
</html>

https://i.sstatic.net/f4HWz.jpg https://i.sstatic.net/I080B.jpg https://i.sstatic.net/MuMb5.jpg https://i.sstatic.net/EW2Fv.jpg

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying a SQL table with AJAX based on radio button selection

I am facing an issue with my webpage where I have three radio buttons and an empty table. The objective is to select a radio button and display a list of employees in the table based on the selection. However, the list does not appear when I click the butt ...

Hmm, seems like there's an issue with the touchable child - it must either be native or forward setNativeProps to

Currently enrolled in a ReactNative course on Coursera, I am facing an error in a 4-year-old course: "Touchable child must either be native or forward setNativeProps to a native component." I am unsure about this error and would greatly appreciate any hel ...

What are the steps to testing an endpoint with Jasmine/Karma?

Within one of my components, there is a method that makes a call to an endpoint in the following manner... private async getRolesAsync(): Promise<void> { const roles = await this.http.get<any>('https://sample-endpoint.com').toProm ...

Update the second dropdown menu depending on the selection made in the first dropdown menu

While I know this question has been posed previously, I'm struggling to apply it to my current situation. In my MySQL database, I have a table named "subject" that includes columns for subject name and subject level. Here's an example: Subject ...

"Functionality of public methods in JavaScript plugin seems to be malfunction

Recently, I made the decision to redevelop a jQuery plugin using vanilla JavaScript. However, I have encountered an issue with getting the public methods to function properly. Despite all other logic working correctly, the public methods are not respondi ...

Apps hosted on Heroku are restricted from accessing CORS, even within the platform's domain

I've been struggling with this problem for a while now. My Nuxt app and service are both hosted on Heroku. After ditching cors(), I added the following code: app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", '*&ap ...

Embedding a thread in an HTML document (Difficult task)

I'm currently working on a method to achieve the following task: Embedding a specific string (such as "TEST") into the content of an HTML page, after every certain number of words (let's say 10). The challenge here is ensuring that the word count ...

Are you looking for methods to alter the elements of a webpage prior to viewing it?

I have created a page with the intention of using it as a tool, but I am facing some challenges due to my limited experience in this field. As a newcomer, I am struggling to achieve certain goals: - My objective is to modify the values of an element on a p ...

No results returned by Mongoose/MongoDB GeoJSON query

I have a Schema (Tour) which includes a GeoJSON Point type property called location. location: { type: { type: String, enum: ['Point'], required: true }, coordinates: { type: [Number], required: true ...

Creating a map in Typescript initialized with a JSON object

In my Typescript class, there is a map that I'm trying to initialize: public map:Map<string,string>; constructor() { let jsonString = { "peureo" : "dsdlsdksd" }; this.map = jsonString; } The issue I'm encounte ...

Customize request / retrieve document cookies

I have successfully implemented a cookie in my express/node.js application. var express = require('express'); var cookieParser = require('cookie-parser') var app = express(); app.use(cookieParser()) app.use(function (req, res, next) ...

Sending a comprehensive form via jQuery ajax without relying on the serialize() method

I've been trying to figure out a way to submit a hefty form using jQuery Ajax, but despite my efforts all day, it seems like there's no straightforward solution. I'm really hoping someone can prove me wrong here. After going through countle ...

Why does the entire page in Next.JS get updated whenever I switch pages?

Currently, I am utilizing Next.JS to create a single-page application website in React. I have successfully set up routing (https://nextjs.org/docs/routing/dynamic-routes) In addition, I have also configured Layouts (https://nextjs.org/docs/basic-features ...

What is the most efficient way to query through a Firestore database containing 5,000 users?

We are currently facing a challenge with our staffing application, which is built using vuejs and a firestore database containing over 5,000 users. Our primary issue lies in the need for a more efficient layout that allows admins to search for users within ...

Display user profile pictures from Vue.js in the Laravel public directory

I have been working on implementing a commenting system and recently incorporated vue.js into my laravel project. One of the features I want to include in my comment area is displaying user profile images from the laravel public folder. However, I am u ...

Stale reference to element detected in Protractor despite implementation of conditional wait

I am encountering an issue within the beforeEach function of my test class. Sometimes, clicking on the usersTab works fine, but other times it results in a StaleElementReferenceException. I have experimented with using protractor.ExpectedConditions such as ...

Create a JavaScript function that continues to execute even after a button has been clicked

Although it may seem like simple logic, I am currently unable to log in. Imagine I have a function called mytimer() stored in a common file that is linked to every HTML page. mytimer(){...........................}; Now, at some point on another page, whe ...

What could be causing the malfunction of this Bootstrap button dropdown?

Initially, I attempted using regular HTML for the dropdown button but encountered issues. As a result, I switched to jsfiddle to troubleshoot. Despite my efforts, the dropdown feature still refused to work. If you'd like to take a closer look, here&a ...

Exploring the capabilities of jQuery's .post function within a custom template form on Wordpress

I am currently developing a customized contact form for a WordPress website and attempting to submit it via ajax with the help of jQuery. However, I am encountering a 404 error in the console when using the $.post function, even though I can access the URL ...

Creating a Node.js application using Express requires careful consideration of file structure and communication methods

Struggling to pass login form credentials to existing JavaScript files for logic and info retrieval. Login page contains a form with POST method. main.js handles the login: main.js module.exports = { returnSessionToken: function(success, error) { ...