fresh map from Google: Coordinates LatLng may not be a number, but my hunch tells me it is

Seeking Assistance with this Issue -

For example, the initial location data appears as:

"Object
Lat: -36.768498
Lng: 174.75895"

However, an error is indicating that the latitude is not recognized as a number. Rather than making adjustments without clear understanding, this newcomer is eager to grasp why this discrepancy exists and how to resolve it :-)

var map, marker;

function initMap() {
    geocoder = new google.maps.Geocoder();

    var centerOfNZ = {lat: -40.8, lng: 173.0};
        map = new google.maps.Map(document.getElementById('map'), {
        zoom: 5.9,
        center: centerOfNZ
    });

    markAllLocations ();
}

function markAllLocations () {
    var locations = [
        ['Auckland','Milford Health Clinic, 50 East Coast Road, Milford', -36.768498, 174.75895],
        ['Christchurch',     'The George, 50 Park Terrace, Christchurch', -43.525776, 172.628387],
        ['Dunedin',          'Aurora on George, 678 George St,   Dunedin', -45.876251, 170.502548],
        ['Hamilton ',        'Medcom Integrative Health Clinic, 32 O\'Neill St, Claudelands,  Hamilton', -37.781234, 175.288198],
        ['Hawke\'s Bay',      'The Doctors Greenmeadows, 524 Kennedy Rd,  Greenmeadows,  Napier', -39.5229328, 176.8685695],
        ['Invercargill',     'The Quest Serviced Apartments, 10 Dee St,  Cnr Dee and Tay Streets,  Invercargill', -46.4131866, 168.3537731],
        ['Nelson',           'Delorenzos Apartments, 43\-55 Trafalgar St,  The Wood,  Nelson', -41.267575, 173.287417],
        ['New Plymouth',     'Quality Hotel Plymouth, Cnr of Courtney and Leach St,  New Plymouth', -39.061173, 174.06889],
        ['Palmerston North', 'Cornwall Motor Lodge, 101 Fitzherbert Avenue,  Palmerston North', -40.3596103, 175.6141897],
        ['Queenstown',       'Level One, 5 Duke St,  Queenstown', -45.03135700, 168.65935960],
        ['Tauranga',         '1416A Cameron Rd Greerton,  Tauranga', -37.729565, 176.129608],
        ['Wanaka',           'C/- Janice Cleghorne, 143 Hunter Cres,  Wanaka', -44.697945,169.167267],
        ['Wellington',       'The Quest on Thorndon, 61\-63 Thorndon Quay,  Thorndon,  Wellington', -41.2760045, 174.7813852],
        ['Whangarei',        'Distinction Whangarei Hotel, 9 Riverside Drive,  Riverside,  Whangarei', -35.723466, 174.327632]
    ];

    for (let count = 0; count < locations.length; count++) {
        let myPos = {                     
                Lat : locations[count][2],
                Lng : locations[count][3]
        };
        console.log(
            count + '  ' + locations[count][0] 
        );
        console.log(myPos);

        marker = new google.maps.Marker(
            { map : map,
              position: myPos,  
              title: locations[count][0] 
            }
        );
    }
}

Answer №1

To utilize the Google Maps API properly, make sure the Marker() function is given a position object containing both lng and lat keys with numerical values. It seems in your scenario, you are working with an object named myPos that uses Lat and Lng (with capital letters), resulting in an error because myPos.lat === undefined.

Answer №2

It has come to light that a minor spelling inconsistency was the root of the error you were encountering. The correct spellings are lat and lng, both written in lowercase instead of capitalized. Additionally, it is advisable to convert the variables into numbers when calling them by utilizing parseFloat(var) or employing the Google Maps method

new google.maps.LatLng(_LAT_,_LNG_)

In my spare time, I made some slight modifications to the original code below - with hope that it will be beneficial.

<!DOCTYPE html>
<html>
    <head>
        <title>Google Maps: New Zealand - Clinical Thermography</title>
        <meta charset="utf-8" />
        <style>
            body,
            html { height:100%;margin:0;padding:0;box-sizing:border-box; }
            #map { width:90%;height:90vh; margin:auto;float:none; }
            /* hide infowindow & pre-format content */
            #info{display:none; padding:1rem;margin:0.25rem;border:1px solid pink;background:white;}
            #info div{margin:0.5rem auto;}
            #info div:before{content:attr(data-label)":";text-transform:capitalize;font-weight:bold;color:black;margin:0 0.5rem 0 0;}
            #info div:after{content:attr(data-value);color:pink;}
        </style>
        <script>
            let map;
            let marker;
            let infoWindow;
            let geocoder;
            let content;

            function initMap() {
                const centerOfNZ = {
                        lat: -40.8,
                        lng: 173.0
                    };
                map = new google.maps.Map( document.getElementById('map'), {
                    zoom: 5.9,
                    center: centerOfNZ
                });

                /* The Geocoder is not used */
                //geocoder = new google.maps.Geocoder();


                infoWindow = new google.maps.InfoWindow({ maxWidth:350, disableAutoPan:false });
                infoWindow.setContent( document.getElementById('info') );

                markAllLocations();
            }

            function markAllLocations () {
                let locations = [
                    ['Auckland',            'Milford Health Clinic, 50 East Coast Road, Milford', -36.768498, 174.75895],
                    ['Christchurch',        'The George, 50 Park Terrace, Christchurch', -43.525776, 172.628387],
                    ['Dunedin',             'Aurora on George, 678 George St,   Dunedin', -45.876251, 170.502548],
                    ['Hamilton ',           'Medcom Integrative Health Clinic, 32 O\'Neill St, Claudelands,  Hamilton', -37.781234, 175.288198],
                    ['Hawke\'s Bay',        'The Doctors Greenmeadows, 524 Kennedy Rd,  Greenmeadows,  Napier', -39.5229328, 176.8685695],
                    ['Invercargill',        'The Quest Serviced Apartments, 10 Dee St,  Cnr Dee and Tay Streets,  Invercargill', -46.4131866, 168.3537731],
                    ['Nelson',              'Delorenzos Apartments, 43\-55 Trafalgar St,  The Wood,  Nelson', -41.267575, 173.287417],
                    ['New Plymouth',        'Quality Hotel Plymouth, Cnr of Courtney and Leach St,  New Plymouth', -39.061173, 174.06889],
                    ['Palmerston North',    'Cornwall Motor Lodge, 101 Fitzherbert Avenue,  Palmerston North', -40.3596103, 175.6141897],
                    ['Queenstown',          'Level One, 5 Duke St,  Queenstown', -45.03135700, 168.65935960],
                    ['Tauranga',            '1416A Cameron Rd Greerton,  Tauranga', -37.729565, 176.129608],
                    ['Wanaka',              'C/- Janice Cleghorne, 143 Hunter Cres,  Wanaka', -44.697945,169.167267],
                    ['Wellington',          'The Quest on Thorndon, 61\-63 Thorndon Quay,  Thorndon,  Wellington', -41.2760045, 174.7813852],
                    ['Whangarei',           'Distinction Whangarei Hotel, 9 Riverside Drive,  Riverside,  Whangarei', -35.723466, 174.327632]
                ];

                /* easier to use `forEach` as the source is an array */
                locations.forEach( location => {
                    /*
                        use `parseFloat` to cast the string to a number/float
                        Alternatively, use `new google.maps.LatLng(location[2],location[3])` 
                        which will do it all nicely for you
                    */
                    marker = new google.maps.Marker({ 
                        map : map,
                        title: location[0],
                        description:location[1],
                        position: {
                            lat: parseFloat( location[2] ),
                            lng: parseFloat( location[3] )
                        }
                    });
                    /* show info for each marker when clicked */
                    google.maps.event.addListener( marker, 'click', function(e){
                        /* get a reference to the infowindow content */
                        content=infoWindow.getContent();
                        /* ensure the content is visible */
                        content.style.display='block';
                        /* add details from marker to the content */
                        content.querySelector('[data-label="name"]').dataset.value=this.title;
                        content.querySelector('[data-label="description"]').dataset.value=this.description;
                        content.querySelector('[data-label="co-ordinates"]').dataset.value=[this.position.lat(),this.position.lng()].join(', ');
                        /* display content */
                        infoWindow.setPosition( e.latLng );
                        infoWindow.open( map );
                    });
                });

            }
        </script>
        <script src='//maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap' async defer></script>
    </head>
    <body>
      <div id='map'></div>
      <!-- use a hidden element as the content for the infoWindow content -->
      <div id='info'>
        <div data-label='name' data-value=''></div>
        <div data-label='description' data-value=''></div>
        <div data-label='co-ordinates' data-value=''></div>
      </div>
    </body>
</html>

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

I'm having trouble understanding why the MUI CORE basic rating code is returning undefined for setValue. Can anyone help

My first experience with MUI CORE was not smooth as I encountered an error when trying to use active rating and the set value is not defined i mport './App.css'; import 'bootstrap/dist/css/bootstrap.min.css'; import Movie from './ ...

The constructor window.CCapture is not valid in Node.js environment

Can anyone help me figure out how to load CCapture in Node.js without using a headless browser for recording canvas stream? Every time I try, I keep running into the error message saying "window.CCapture is not a constructor." If you are familiar with the ...

Updating the id token in VueJs using Axios interceptor when it expires

I need to implement an axios interceptor that will add the idToken as an authorization header to every axios call, and also refresh the idToken if it has expired before making any call. My current code for this task is as follows: axios.interceptors.requ ...

Executing multiple child processes in a loop with asynchronous operations and collecting the output after the loop concludes

Here's a snippet of code I've been working on... const { exec } = require('child_process'); const Main = async () => { const result = await RetrieveAllItems(); console.log('output', result); }; const RetrieveAllI ...

Which is more recommended to use in AJAX (XMLHttpRequest) - eventListener or readyStateChange method?

As I revisited a video from WWDC12 discussing advanced effects with HTML5, I couldn't help but notice that for the demo they utilized req.addEventListener("load",callback,true) instead of the usual onreadystatechange. This made me wonder: what differ ...

I attempted to implement an AJAX partial refresh for my HTML, but unfortunately, it did not have the

I've been attempting to implement Ajax to locally load the page, but unfortunately, the code below isn't functioning as expected. My intention is to transmit the 'MSG' information from 'views' to Ajax and refresh the page loca ...

Error handling in Angular is not properly managing the custom exception being thrown

I am currently working on an Angular 12 application and I have a requirement to implement a custom ErrorHandler for handling errors globally. When I receive an error notification from the backend, I subscribe to it in the ToolService using this.notificati ...

Instructions on how to save HTML "innerHTML" along with attributes to a text document

I'm currently developing an HTML export feature from a DIV tag that includes various elements and attributes. HTML: <div id="master"><span class="classname">content goes here</span></div> <span class="download" onclick="ca ...

Having trouble displaying a popup dialog box in ASP.NET using JavaScript

I am trying to implement a popup dialog box in ASP.NET using JavaScript, but it's not working as expected! Below is the code I am using: <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal< ...

Implementing Bootstrap tooltips in content that can be scrolled

I need help with positioning two containers, which you can view in this FIDDLE. Both containers may contain a lot of content, so I have applied overflow: auto to both of them. This is the HTML structure: <div id="maincontainer"> <d ...

Tips for asynchronously modifying data array elements by adding and slicing

I am facing an issue in my vuejs application where I need to modify an array of items after the app has finished loading. My current setup looks like this: var n = 100; var myData = []; function loadMovies(n){ // async ajax requests // add items to ...

Tips for implementing FontAwesome in Nuxt3

I'm facing some issues trying to implement FontAwesome in my NuxtJS project, and for some unknown reasons, it's not working as expected. Let's take a look at my package.json: { "private": true, "scripts": { " ...

Retrieve the value from the URL by parsing it using JSON

My goal is to extract the asciiName from a specific URL: http://services.gisgraphy.com/geoloc/search?lat=21.283300399780273&lng=72.9832992553711&radius=10000<br> I am utilizing ajax jsonp for this task. Below is the complete code snippet ...

Encountering ENOENT error with Node.js file preview

I am attempting to utilize the filepreview tool to extract an image from a docx document. I have successfully installed it using the command npm install filepreview. This is the code snippet I am working with: const filepreview = require('fileprevie ...

NodeJS: The module failed to automatically register itself

Exploring the capabilities of IBM Watson's Speech to Text API, I encountered an issue while running my NodeJS application. To handle the input audio data and utilize IBM Watson's SpeechToText package, I integrated the line-in package for streami ...

Exporting a named export for every HTTP method is the way to go with NextJs

I'm currently working on a project to create an Airbnb clone using NextJs. The tutorial I'm following is using an experimental version, while I've opted for the latest version of NextJs. One aspect that's been causing confusion for me i ...

The second jQueryUI datepicker instance flickers and vanishes when the show() function is triggered

I currently have two jQueryUI datepickers integrated into my webpage. The initialization code for both is as follows: jQuery("#departureDate").datepicker({ beforeShow: function() { getDatesForCalendar("outbound"); }, numberOfMonths: 3 ...

The dynamically generated table will only show the most recently added data

Currently, I am delving into the world of JavaScript to tackle an interesting challenge. Here's the scenario: I have a dropdown list populated with stream names derived from an array. Whenever a selection in this array changes using `onchange()`, I wa ...

Personalize the "set up notification" PWA on React

Is it possible to customize this default design, including the picture, title, description, and background? I made changes in manifest.json, but nothing seems to have happened. Here is a picture of the random install prompt that I would like to customize ...

When Selenium in JavaScript cannot locate a button element, use `console.log("text")` instead

I am trying to capture the error when there is no button element available by using console.log("No element"). However, my code is not working as expected. const {Builder, By} = require("selenium-webdriver"); let driver = new Builder().forBrowser("chrome ...