Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try Catch for error message in google maps api

I an using javascript and am getting an message that I have exceeded my daily request quota for this API. Is there a way to capture this error message in a try catch block so when I go over my quota I can execute another piece of code. I have seen several similar posts, but nothing that has been helpful. Here is my code.

(function (window, google, lat, lng) {
           var options = {
               center: {
                   lat: Number(lat),
                   lng: Number(lng)
               },
                 zoom: 5,
                 disableDefaultUI: true,
                 scrollwheel: true,
                 draggable: false
           },
           element = document.getElementById('map-canvas')
           var map = new google.maps.Map(element, options)
       }(window, window.google, result[i]['latitude'], result[i]['longitude']));
like image 211
Aaron Avatar asked Jul 26 '17 22:07

Aaron


People also ask

How can I tell if Google Maps API is working?

Go to the Credentials section, which can be accessed from the left side bar under Google Maps Platform > Credentials. Check that the API key you currently use on your website is listed. If that's not the case, switch to a different project, and check the credentials there.

Why isn't my Google Maps API working?

There are a several reasons why your google maps may not be working, the most common issue being no Google Map API key set or set incorrectly. To use the Google Maps JavaScript API, you must register your app project on the Google Cloud Platform Console and get a Google API key which you can add to your app.

How do I fix Google Maps API key?

Go to Theme Options > Other Options > Miscellaneous and paste copied API key to Google Maps API Key field: Click Save All Changes and you should be able to view Google Maps on your site.


Video Answer


1 Answers

Update As per the documentation:

if you want to programmatically detect an authentication failure (for example to automatically send an beacon) you can prepare a callback function. If the following global function is defined it will be called when the authentication fails. function gm_authFailure() {//code}

Here is a list of errors that the gm_authFaliure function should be able to catch. It also mentions a OverQuotaMapError error.

As per the documentation:

if too many requests are made within a certain time period, the API returns an OVER_QUERY_LIMIT response code.

So you should check the response code. If the Google maps javascript library does not allow to access to the response code then I recommend making a HTTP request to the API to get the response code.

function initMap(window, google, lat, lng) {
   var options = {
       center: {
           lat: Number(lat),
           lng: Number(lng)
       },
       zoom: 5,
       disableDefaultUI: true,
       scrollwheel: true,
       draggable: false
   },
   element = document.getElementById('map-canvas'),
   map = new google.maps.Map(element, options);
};

function googleMapsCustomError(){
    alert('Google Maps custom error triggered');
}

// if you want to respond to a specific error, you may hack the
// console to intercept messages.
// check if a message is a Google Map's error message and respond
// accordingly
(function takeOverConsole() { // taken from http://tobyho.com/2012/07/27/taking-over-console-log/
    var console = window.console
    if (!console) return

    function intercept(method) {
        var original = console[method]
        console[method] = function() {
           // check message
           if(arguments[0] && arguments[0].indexOf('OverQuotaMapError') !== -1) {
             googleMapsCustomError();
           }
           
            if (original.apply) {
                // Do this for normal browsers
                original.apply(console, arguments)
            } else {
                // Do this for IE
                var message = Array.prototype.slice.apply(arguments).join(' ')
                original(message)
            }
        }
    }
    var methods = ['error']; // only interested in the console.error method
    for (var i = 0; i < methods.length; i++)
        intercept(methods[i])
}())
<!DOCTYPE html>
<div id="map-canvas"></div>

<script>
// Notice i am defining this within my html file, just to be sure that this function exists before the Google Maps API is loaded.
window.gm_authFailure = function() {
    // remove the map div or maybe call another API to load map
   // maybe display a useful message to the user
   alert('Google maps failed to load!');
}

window.showMap = function() {
  var lat = -34.397,
      lng = 150.644;
  initMap(window, window.google, lat, lng);
};
</script>

<!-- We are passing an invalid API key. Also notice that we have defined 'callback' as 'showMap' which means that when the Google API JavaScript library is finished loading it will call the 'showMap' function. -->
<script src="https://maps.googleapis.com/maps/api/js?key=INVALID_API_KEY&callback=showMap"
    async defer></script>
like image 163
Lucky Soni Avatar answered Sep 17 '22 17:09

Lucky Soni