Encountering an issue when using both the Google Maps API and Google URL Shortener API within the same program

Recently, I developed a program that involves passing data to an iframe through a URL. However, due to the limitation of Internet Explorer supporting only 2083 characters in a URL, I decided to use the Google URL Shorten API to shorten the URL before sending it as an argument. The plan was to later retrieve the long URL using the shortened URL and extract the necessary data.

The challenge I encountered was calling two APIs within the same program.

Below is a snippet of the code where I fetch the long URL from Google and then initialize the map. According to my logic, we need to first extract the data from the long URL before we can pinpoint the markers on the map. Therefore, initializing the map before calling the Google shorten URL API is not feasible.

Check out the code below -

<html>
<head>
</head> 
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
function makeURLShortenApiCall(){
var shortUrl="";
gapi.client.setApiKey('AIzaSyDQo3yvYTgw7pdfGTRz6zanq41rhymA-N8');
gapi.client.load('urlshortener', 'v1',function(){

var shortUrl="http://goo.gl/AWGcY4";

    var request = gapi.client.urlshortener.url.get({
      'shortUrl': shortUrl,
    'projection':'FULL'
    });
    request.execute(function(response) 
    {

        if(response.longUrl!= null)
        {
            console.log(response.longUrl);
            initialize();
        }
        else
        {
            alert("error: "+response.error);
        }

    });

});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=makeURLShortenApiCall"></script>
<script>
function initialize() {
  var mapProp = {
    center:new google.maps.LatLng(51.508742,-0.120850),
    zoom:5,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  };
  var map=new google.maps.Map(document.getElementById("Map"),mapProp);
}
</script>
<body>
<div id="googleMap" style="width:500px;height:380px;" class="absolute"></div>
</body>
</html>

Upon running the program, an error message popped up saying -

Uncaught TypeError: Cannot read property 'offsetWidth' of null

I'm currently stuck with this issue. Any suggestions on how to troubleshoot and solve this problem?

Answer №1

I actually identified the issue.

The problem arose because

var map=new google.maps.Map(document.getElementById("Map"),mapProp);

The Map id did not correspond to the div id named googleMap

<div id="googleMap" style="width:500px;height:380px;" class="absolute"></div>

Nevertheless, I appreciate your assistance.

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

Is it possible to determine which child element is currently in view within a scrollable parent div?

In an attempt to replicate a "current page" feature using divs, similar to a PDF reader. document.addEventListener("DOMContentLoaded", function(event) { var container = document.getElementById("container"); container.onscroll = function() { let ...

Create a JavaScript JSON object using a for loop

I am working on creating an object similar to this var flightPlanCoordinates = [ {lat: 37.772, lng: -122.214}, {lat: 21.291, lng: -157.821}, {lat: -18.142, lng: 178.431}, {lat: -27.467, lng: 153.027} ]; Here is my attempt so far for (i = 0; ...

What is the best way to create a button with this functionality?

In the form that I have created, it is opened in a bootstrap modal style. This form contains a button that, when clicked, triggers an alert box to appear. The code snippet used for this functionality is as follows: echo "<script>"; echo "alert(&apos ...

Submit button on Ajax form causes automatic page refresh

After adding a simple Ajax form to my WordPress website, I encountered an issue where the validation works fine, but instead of sending the email, the form refreshes after submitting. Here is the code snippet: <script type="text/javascript"> jQ ...

Shifting the MUI DataGrid Pagination table to the left with CustomPagination: A step-by-step guide

Hey everyone, I am currently diving into the MUI data grid to gain a better understanding. In order to meet my design requirements for a table view, I have incorporated the DataGrid component from MUI. For pagination, I am utilizing their custom implementa ...

Testing the speed of the client's side

In my quest to create an application that allows users to conduct a speedtest on their WiFi network, I have encountered some challenges. While standalone speedtest apps like Speedtest.net and Google exist, server-based speed test modules from NPM are not s ...

I encountered an issue with Array map when attempting to access the data during a dynamic rendering process

function UserTransactionsComponent1() { const [accounts, setAccounts] = useState(); useEffect(() => { async function fetchData() { const res = await fetch( 'https://proton.api.atomicassets.io/atomicassets/v1/accounts' ...

What is the process for generating a null result cursor upon publication?

Is it possible to return an empty cursor in Meteor? Meteor.publish('example', function(id) { check(id, Match.Maybe(String)) if (!this.userId) return [] }) Although I want the publication to return an empty result when the user is not lo ...

Ng-Repeat is generating empty list items

When I view this code in my browser, I see two list items, but there is no content displayed within them. The loop seems to be functioning correctly, but the items are not pulling any information from my list. I have revised my submission to accurately re ...

Uncertain about the ins and outs of AJAX

I am a complete beginner in web development. Although I have studied JavaScript and HTML through books, my understanding is still limited. I have never worked with AJAX before and find most online examples too complex for me to follow. My goal is to crea ...

Having trouble retrieving coordinates from AJAX request to Google Maps API?

I am currently developing a weather application and one of the initial steps is to retrieve the longitude and latitude coordinates for a specific city based on its name. To achieve this, I am utilizing Google Maps API to gather the necessary information. ...

Interactive front end design for decision trees

On the front end, I aim to enable users to influence the outcome of a Decision Tree based on their selections. For my Django-React App, I have adopted the style and tree example from the codeplayer. You can find it here: I am tasked with creating an unor ...

"Enhance your Django website with a dynamic voting button using AJAX

I am working on a project where I have implemented the following code: (r'^oyla/(\d+)/$', oyla), Here is the view associated with this code snippet: @login_required def oyla(request, id): if request.is_ajax(): entry = Entry.ob ...

Adjustable value range slider in HTML5 with ng-repeat directive in AngularJs

I am facing a problem with my HTML5 range slider. After setting a value (status) and sending it to the database, when I reload the page the slider's value is always set to '50'. The slider is being generated within an ng-repeat from AngularJ ...

"Owlcarousel Slider: A beautiful way to showcase

Currently, I am working on a project that involves implementing a slider. Since I lack expertise in JavaScript, I opted to use a plugin called owlcarousel. The challenge I'm encountering relates to the sizing of the container for the items. I'm ...

The problem stemming from the implementation of the useNavigate() Hook in a personalized React-Admin application

I've encountered a complex issue in my React-Admin application. Whenever I attempt to utilize the useNavigate() hook within my custom login component (MyLoginPage), an error message pops up: [Route] is not a <Route> component. All component chi ...

The Vue-router is constantly adding a # symbol to the current routes, and it's important to note that this is not the typical problem of hash and

After setting up my router file using Vue 3, it looks like this: import { createRouter, createWebHistory } from "vue-router"; import Home from "../views/Home.vue"; const routes = [ { path: "/", name: &quo ...

Discovering a specific URL link element within the DOM using webdriver.io

I am currently utilizing webdriver io for conducting tests on a webpage. I am in need of verifying the existence of an element with a specific href on the page. I have attempted to achieve this using the following snippet var client = webdriverio.remote ...

Guide on transforming Json information into the preferred layout and iterating through the loop

Currently, I am diving deep into the world of JSON and feeling a bit puzzled by data formats, arrays, objects, and strings. First things first, I'm in need of data structured like this (on a jQuery page). Would this be considered an object or an arra ...

Ensuring type signatures are maintained when wrapping Vue computed properties and methods within the Vue.extend constructor

Currently, I am trying to encapsulate all of my defined methods and computed properties within a function that tracks their execution time. I aim to keep the IntelliSense predictions intact, which are based on the type signature of Vue.extend({... Howeve ...