Issue with Java Script inheritance in google.maps.OverlayView not functioning as expected

UPDATE: After spending another day working on this, I believe I have identified the issue, although it is not yet confirmed. Once I have verified the solution, I will update this post with an answer.

My current understanding is that the problem arises from loading the Google Maps API via the AjaxLoader utility in GWT. This causes the google.maps.OverlayView to not be resolved when the javascript library containing the USGSOverlay code is being loaded, resulting in the line

USGSOverlay.prototype = google.maps.OverlayView();

clearing out the prototype information for the object. I am now in the process of dynamically loading the USGSOverlay library after the completion of the AjaxLoader.loadApi() method.

Another indication of the issue: Setting the prototype to google.maps.OverlayView() disrupts both the inheritance of USGSOverlay and a test object added at the end of the file. If I modify the inheritance of my USGSOverlay object by adding these lines at the start of the JS library file,

function OverlayParent() {
}

OverlayParent.prototype.setMap= function(map) {}

and change my USGSOverlay.prototype to equal new OverlayParent(), the inheritance works properly and I no longer encounter the exception this.SetMap(map) is not a function.

If anyone has a ready-made solution for this issue, I would appreciate a link, but I am exploring a solution similar to this approach DOM-Based On-Demand Javascript


Although I am new to JavaScript, I am a seasoned programmer, and this particular problem has me puzzled. Despite several days of work, I have made little progress. In my latest attempt, I am almost exactly replicating the code from Google Maps JavaScript API v3 CustomOverlay. The documentation for OverlayView states "You should inherit from this class by setting your overlay's prototype to new OverlayView.prototype." While I don't believe the issue I'm facing is limited to the Google Maps API, here is the code snippet:

function USGSOverlay(bounds, image, map) {
  // Initializing all properties.
  this.bounds_ = bounds;
  this.image_ = image;
  this.map_ = map;

  // Property to store the image's div.
  this.div_ = null;

  // Explicitly calling setMap() on this overlay
  this.setMap(map);
}

USGSOverlay.prototype = new google.maps.OverlayView();
USGSOverlay.prototype.constructor=USGSOverlay;

Followed by implementations for onAdd, draw, and onRemove as previously described.

While stepping through the code everything seems fine until the call to the inherited method setMap throws the following exception:

Cannot load Google Maps API to your browser (TypeError): this.setMap is not a function;

Firebug reveals that the proto variable is not set, indicating that the inheritance is not taking place. Initially, I was calling the constructor via a GWT JSNI function, but to eliminate that possibility, I created a second test JavaScript object to verify the parameters passed are correct. Here is the function:

function TestUSGSOverlay(map,inBound) {
  var swBound = new google.maps.LatLng(39.5, -106.0);
  var neBound = new google.maps.LatLng(40.0, -105);
  var bounds = new google.maps.LatLngBounds(swBound, neBound);
  var sw = inBound.getSouthWest();
  var ne = inBound.getNorthEast();

  var marker = new google.maps.Marker({
      position: sw,
      map: map,
      title:"South West Corner"
  });

  var marker2 = new google.maps.Marker({
      position: ne,
      map: map,
      title:"North East Corner"
  });

  var srcImage = 'images/DenverWest.png';
  var usgsMap = new google.maps.GroundOverlay(srcImage,bounds);
  usgsMap.setMap(map);
  this.overlay = new USGSOverlay(bounds, srcImage, map);
 }

If I exclude the last line, the map displays correctly between the South West and North East markers with the U.S. Geological Survey map. Although my actual requirement is to display text in a table div, for testing purposes, I substituted the map display.

I have read several articles on prototype inheritance, and while I understand it is complex, none of my attempts have led to any progress. The same behavior occurs in IE 8 as well as Firefox. Any advice or guidance you can provide would be greatly appreciated, as I am running out of ideas.

Answer №1

I successfully identified the issue and resolved it. While similar to a race condition, I am hesitant to categorize it as such since the correct sequence of events will never occur.

The problem stemmed from my application loading the Google Maps API through the Google API's AjaxLoader object, while my USGSOverlay javascript library was being loaded as part of the page load process. The asynchronous loading by AjaxLoader happens after the javascript has already been loaded, either from the GWT entry point method or in HTML world onLoad event. Albeit there were no errors reported, the inheritance of the USGSOverlay object was incorrect even though the javascript constructor existed. (By the way, does anyone know of tools that could identify this scenario?)

The debugging in Firebug revealed the invalid inheritance state due to the absence of a __proto__ member variable in the USGSOverlay object. To rectify this, I included logic to dynamically load the USGSOverlay javascript library within the onLoad callback function passed into AjaxLoader's loadApi method. However, a remaining issue was that this approach depended on the DOM to detect additions to the page's head and execute the script load, resulting in a race condition where the library often wasn't loaded when needed.

This article outlines how I implemented dynamic loading of the JavaScript: DOM Based on Demand Javascript

To circumvent the race condition caused by the library not being loaded, I simply added a

if (typeof USGSOverlay != 'undefined') { ... }

check before calling the new USGSOverlay(...) method. Since my OverlayView derived object is related to a hover effect, this basic exception handling sufficed for my needs. A more sophisticated solution would be necessary if your Overlay is integral to the initial display, but that's a challenge you'll have to tackle :). There are various discussions on strategies for that situation.

Answer №2

I encountered a similar issue and wasn't keen on utilizing the method of dynamically loading the custom overlay script as outlined in your response.

How do you invoke the initialize() function?

In my case, I loaded the Google Maps API in this way:

<!-- I left out sensor=false to prevent scrollbars -->
<script type="text/javascript" 
    src="http://maps.googleapis.com/maps/api/js?callback=initialize">
</script>

Note the callback=initialize. This was causing the issue of timing conflicts. To resolve this, I removed callback=initialize from the API query string and appended the following line at the end of my init.js script:

window.onload = initialize();

This approach worked for me. Hopefully, it proves helpful to you too!

Answer №3

Based on the information provided in the documentation, it appears that Google Charts was officially released on February 23, 2016 and is the current version.

In my research, I came across some updates that needed to be implemented.

I trust this will be of assistance!

Best regards, Jayden

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

Methods to Maintain Consistent HTML Table Dimensions utilizing DOM

I am facing an issue with shuffling a table that contains images. The table has 4 columns and 2 rows. To shuffle the table, I use the following code: function sortTable() { // Conveniently getting the parent table let table = document.getElementById("i ...

Exploring the power of jQuery and Ajax together

Today seems to be one of those days where even the simplest tasks become a challenge. I'm sorry if this question has been asked before, but I'm struggling with a basic issue. I want to dynamically update text on a website using a text file, and w ...

When using JSON.stringify on a map object, it returns an empty result

var map1= new Map(); map1.set("one",1); var map2 = new Map(); map2.set("two",2); concatMap = {}; concatMap['one']= map1; concatMap['two']= map2; JSON.stringify(concatMap); //outputs : "{"one":{},"two":{}}" I als ...

Unable to connect beyond the local network using Socket.io

server.js import { Server } from "socket.io"; const io = new Server(8000); io.on("connect", (socket) => { console.log(`connect ${socket.id}`); socket.on("ping", (cb) => { console.log("ping"); ...

Having trouble getting the vue-slick-carousel to function properly when using it from the CDN

Struggling to implement a small app using the CDN script at , but so far no success. I'm a novice with vue.js and unsure if I need to import anything. According to the documentation, importing is required: Vue-slick-carousel Following this structure ...

Building a loading bar using dots

<span class="dot"></span> <span class="dot"></span> <span class="dot"></span> <span class="dot"></span> <span class="dot"></span> <span class="dot"></span> <span class="dot">< ...

Select a file and upload an image promptly after it is chosen

Is there a way to automatically upload an image once a user selects a file in their browser? Similar to how it works on Facebook, where users can choose a file for their cover or profile image and then the upload process begins. Currently, all I have is ...

What is the best way to integrate my custom JavaScript code into my WordPress theme, specifically Understrap?

I am looking to enhance my website with a sticky navbar positioned directly under the header, and I want it to stick to the top of the page as users scroll down. Additionally, I want the header to disappear smoothly as the user scrolls towards the navbar. ...

What is the process for importing an md file in a create-react-app project using JavaScript?

Attempting to execute the blog example provided on Material UI's getting started page. However, encountering an issue with the source code: Inside blog.js import post1 from './blog-post.1.md'; . . . return( <Main>{post1}<Main/> ...

Establish a WebSocket connection via Meteor.js

How do we establish a Websockets connection in Meteor? Can we achieve this using the following code: ws = new WebSocket('ws://localhost/path'); ws.on('open', function() { ws.send('something'); }); ws.on('message&apo ...

Is it possible to ensure only one value is set as true in useReducer without manually setting the rest to false

I am seeking a more efficient method to ensure that only one value is set to true while setting the rest to false I came across this Python question and answer recommending an enum (I am not very familiar with that concept) Currently, I have the followin ...

Difficulty accessing `evt.target.value` with `RaisedButton` in ReactJS Material UI

My goal is to update a state by submitting a value through a button click. Everything works perfectly when using the HTML input element. However, when I switch to the Material UI RaisedButton, the value isn't passed at all. Can someone help me identif ...

Attempting to scroll through a webpage and extract data using Python and Selenium in a continuous manner

Recently, I posed a question (you can find it here: Python Web Scraping (Beautiful Soup, Selenium and PhantomJS): Only scraping part of full page) that shed light on an issue I encountered while attempting to scrape all the data from a webpage that updates ...

Unable to interact with the page while executing printing functionality in

component: <div class="container" id="customComponent1"> New Content </div> <div class="container" id="customComponent2"> different content </div> ...

An issue has occurred: The necessary parameter (Slug) was not included as a string in the getStaticPaths function for the /post/[Slug] route

Hello, I've recently embarked on a tutorial journey to create the ultimate Modern Blog App using React, GraphQL, NextJS, and Tailwind CSS. However, I encountered an error that's giving me some trouble specifically when trying to access a post. He ...

The content located at “http://localhost:3000/public/static/” was restricted because of a mismatch in MIME type (text/html) which triggered the X-Content-Type-Options:nosniff protocol

https://i.stack.imgur.com/7Etn7.png Every time I try to run the server with nodemon, I keep encountering the error mentioned in the title. Below is the code snippet from the JavaScript file: const express = require('express') const path = requir ...

How to handle Component binding change events in AngularJS

I have developed a component in AngularJS that displays data. However, when the customer binding changes, I need to call a service in the component controller, but it is not updating. Below is the code snippet: In my Test1.html file: <tab-customer tit ...

Creating dynamic dropdown menus using JSON files in jQuery mobile is a useful technique for enhancing user experience on

I am working with a massive table (8 MBytes) that I need to filter using a small JavaScript application. The process works as follows: Countries Regions Skills I want the user to select one country, one region, and multiple skills as filters. Based on ...

Having Trouble Sending Text to InputBox Using Selenium WebDriver

Greetings everyone Can someone guide me on how to use Selenium to input a Login and Password in an Alert Dialog Box? Upon loading the webpage, the alert is already displayed: https://i.stack.imgur.com/F1O5S.png I have attempted the following code: Str ...

Ways to resolve eslint typedef error when using angular reactive forms with form.value

I am facing an issue with my formGroup and how I initialized it. Whenever I try to retrieve the complete form value using form.value, I encounter an eslint error related to typecasting. userForm = new FormGroup<user>({ name: new FormControl<st ...