What is causing the error "Cannot read property 'getCenter' of undefined" to appear when I attempt to view my embedded Google Map?

In setting up the Google map on my webpage, I follow this process:

var initialize = function(latitude, longitude, boundaries) {

            // Using selected latitude and longitude as starting point
            var myLatLng = {lat: selectedLat, lng: selectedLong};

            // If the map has not been created yet...
            if (!map){
                // Create a new map and add it to the index.html page
                var map = new google.maps.Map(document.getElementById('map'), {
                    zoom: 12,
                    center: myLatLng
                });
            }

            if(boundaries.length > 0){
                // We don't have permission to use the user's real GPS location
                var bounds = new google.maps.LatLngBounds(
                    new google.maps.LatLng(boundaries[0], boundaries[1]),
                    new google.maps.LatLng(boundaries[2], boundaries[3]) );

                map.fitBounds(bounds);
            }else{
                // We have permission, so let's mark their location with a marker
                // Set initial location as a bouncing red marker
                var initialLocation = new google.maps.LatLng(latitude, longitude);

                var marker = new google.maps.Marker({
                    position: initialLocation,
                    animation: google.maps.Animation.BOUNCE,
                    map: map,
                    icon: 'http://www.google.com/mapfiles/dd-start.png'//'http://maps.google.com/mapfiles/ms/icons/red-dot.png'
                });
                //lastMarker = marker;

            }


            refreshDataOnMap(longitude, latitude, map);

As shown above, I attempt to pass the created map to the refreshDataOnMap method:

   var refreshDataOnMap = function(long, lat, mymap) {

        console.log("refresh!!");
        var calculatedDistance = calculateRadiusInMiles(mymap);
   }

This method then calls calculateRadiusInMiles:

// Get the visible map radius
        var calculateRadiusInMiles = function(map){

            var bounds = map.getBounds();

            var center = bounds.getCenter();
            var ne = bounds.getNorthEast();

            // r = radius of the earth in statute miles
            var r = 3963.0;

            // Convert lat or lng from decimal degrees into radians (divide by 57.2958)
            var lat1 = center.lat() / 57.2958;
            var lon1 = center.lng() / 57.2958;
            var lat2 = ne.lat() / 57.2958;
            var lon2 = ne.lng() / 57.2958;

            // Distance = circle radius from center to Northeast corner of bounds
            var dis = r * Math.acos(Math.sin(lat1) * Math.sin(lat2) +
                    Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1));
            return dis;
        };

Upon checking the console, I receive the following information:

refresh!!

angular.js:12520 TypeError: Cannot read property 'getCenter' of undefined at calculateRadiusInMiles (gservice.js:112) at refreshDataOnMap (gservice.js:48) at initialize (gservice.js:214) at Object.googleMapService.refresh (gservice.js:36) at Object. (gservice.js:225) at Object.invoke (angular.js:4523) at Object.enforcedReturnValue [as $get] (angular.js:4375) at Object.invoke (angular.js:4523) at angular.js:4340 at getService (angular.js:4482)(anonymous function) @ angular.js:12520(anonymous function) @ angular.js:9292Scope.$apply @ angular.js:16157bootstrapApply @ angular.js:1679invoke @ angular.js:4523doBootstrap @ angular.js:1677bootstrap @ angular.js:1697angularInit @ angular.js:1591(anonymous function) @ angular.js:29013fire @ jquery.js:3182self.fireWith @ jquery.js:3312jQuery.extend.ready @ jquery.js:3531completed @ jquery.js:3547

refresh!!

Due to this error, I am unable to properly utilize the map on my page. It seems like the map loads after attempting to call its properties, but how can I prevent this issue?

Thank you for any insights.

EDIT===========

One important detail worth mentioning for debugging purposes:

The Google map is initially loaded and centered based on the user's IP address, but once the browser detects GPS data, the map reloads and focuses on that specific GPS point. That explains why you see refresh!!! printed twice in the console log.

Answer №1

It seems that the issue is with the bounds being undefined, which makes map invalid. Have you verified the values of map and calculateRadiusInMiles()? Also, double-check if bounds has been properly set and if the map has finished loading.

For more information about Google Maps Api v3 - getBounds is undefined click here

Edit to provide clarity:

You can listen for an event in version 3 that handles this situation:

`google.maps.event.addListener(map, 'bounds_changed', function() {
     alert(map.getBounds());
});

Alternatively, you can use:

`google.maps.event.addListener(map, 'idle', function() {
     alert(map.getBounds());
});

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

Interactive tabs displaying real-time information

My goal is to create tabbed content based on a tutorial I found online. Following the tutorial step by step works perfectly, but now I want to take it a step further and make the tabs dynamic. The issue arises when some tabs have no content, so I need to g ...

What is the best way to create a rapid reference in AngularJS for dynamically generated items using ng-repeat?

Being new to angularjs, I am looking to create a simple and quick reference between my anchors and paragraphs/inputs based on what is clicked in my angular web app. Currently, I have generated 3 table rows with 1 table data using ng-repeat. When I click on ...

The Splice function is malfunctioning due to issues with the object (the indexOf function is not recognized)

I am currently dealing with an object that looks like this: Object {val1: "Hello", val2: "", dt1: "pilo1", dt2: "pilo2", lo1: "log1"} My goal is to remove any keys within the object that have empty values (""). I attempted the following code snippet: ...

Refresh the Angular controller for the modal every time it is accessed

Separate controllers have been defined for the base page and modal on that page, each containing a form with values retrieved from local storage. The issue arises when the modal controller loads the value for the elements upon DOM load, showing the same va ...

Refreshing the Angular page using ng-route in html5 mode fails to redirect to index.html

My goal is to implement html5 mode for my mean app. Below is the view router code in my angular script: app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider // define r ...

Issue with Yup and Formik not validating checkboxes as expected

I'm struggling to figure out why the validation isn't functioning as expected: export default function Check() { const label = { inputProps: { "aria-label": "termsOfService" } }; const formSchema = yup.object().shape({ ...

After updating Laravel Mix, I found that I am unable to pass the parent component's object as a prop in Vue

After updating Laravel Mix to the latest version in my project, I started encountering Vue errors. One particular issue that I am struggling with involves a component I have created: <template> <div> <ChildComponent :context="th ...

Restricted footage accessible through RESTful API

Hey there! I'm currently working on implementing authentication protected audio/video streaming in an Angular app using REST API. The main objective is to ensure that the audio/video content is secure and not accessible to users who are not logged in. ...

Show the user's chosen name in place of their actual identity during a chat

I'm facing an issue where I want to show the user's friendly name in a conversation, but it looks like the Message resource only returns the identity string as the message author. I attempted to retrieve the conversation participants, generate a ...

Efficiently process 100 tasks per minute using a microservice architecture

I have a node.js application that needs to perform the following tasks: Retrieve zip files, extract them (containing JS module files with key-value pairs - usually 5-8 files per request) Analyze these files, create new ones from the analysis, and ...

Find all elements within JSON data using lodash.js

Hello friends, I'm dealing with a JSON object: var companies = [ { id: 1, name: "Test Company", admin: "Test Admin" }, { id: 2, name: "Another Company", admin: "Test Admin", country: 'Spain' }, { id: 3, name: "New Company", ad ...

Send information to a function until the array reaches its maximum length

I am facing a challenge where I have a function that accepts multiple arrays as arguments, but the data available to me is already within an array called mainArr. This mainArr consists of several array items that need to be passed as arguments to the funct ...

Ldap.js: exploring nested searches

My current task involves using ldapjs to conduct a search where the filter is dependent on the outcome of a preceding search. ldapClient.search(base1, opts1, (err1, res1) => { res1.on("searchEntry", entry => { const myObj = { attr1: entr ...

Displaying data from a JSON array in Angular

I can't seem to understand what mistake I'm making in my code here. My goal is to access data from the months array within the JSON structure provided below. Here is my schema: var mongoose = require('mongoose'); var Schema = mong ...

Signs that indicate Angular has completed deferring

I'm having trouble grasping Angular's deferring and promises. I want to hide a "loading" message once all promises have been completed. Here's an example of my code: $scope.buildTeam = function () { $scope.Message = "loading..."; v ...

I am eager to develop a Loopback model tailored specifically for handling this JSON data

"US Virgin Islands": [ "Charlotte Amalie", "Christiansted", "Frederiksted", "Kingshill", "St John Island" ], I'm currently working with a JSON file that contains country names and corresponding cities. I want to store this data in my database using M ...

What is the best way to execute an API that relies on a variable determined by a previous API call?

I am facing a challenge in creating a node seed script using an API that is paginated with a property called 'numberOfPages'. My goal is to seed a database on each page by running a for loop based on the value of 'numberOfPages'. Howev ...

Change the color of the text based on which classes the visitor is currently viewing on the page

I have a sidebar menu in plain html for page navigation, like this: <div class="sidebar"><h2>About us</h2> <h3><a href="#chapter1" class="link">Chapter 1</a></h3> <h3><a href="#chapter2" class="link"> ...

Activating HTML 5 Mode within AngularJS 1.2

I'm currently developing an application that requires the use of HTML 5 mode. The challenge I am facing is that as I transition an existing website to AngularJS 1.2, I need to eliminate '#' tags from my URLs. Below is my current configuratio ...

The communication between Node.js Express and the front end is experiencing synchronization issues

I'm facing an issue where a property is mysteriously disappearing when I try to send an object from my nodejs server to the front end. server router.post('/cart/retrieve', (req, res) => { let cart = req.session.cart; let prodId ...