Create a loop that generates a new Google Map Marker for each JSON object stored in the database

My friend and I are collaborating to develop a Google Map marker for each entry in a table. Although I have implemented a loop, I am uncertain if it is correct. The map functions properly, allowing me to insert normal markers and cycle through the entries to append them to a div. However, when attempting to incorporate the marker code within the loop, I encounter numerous errors in the console:

InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number

InvalidValueError: setMap: not an instance of Map; and not an instance of StreetViewPanorama

Could this indicate that the database has failed to store the latitude/longitude as numbers? Below is a simplified version of the code that I currently have:

$.ajax({
    type: 'POST',
    url: 'getAllJson.php',
    success: function(jsonData) {
        var obj = (jsonData);
        $.each(obj, function(key,value) {
            //console.log(key, first, value[1], value[2]);
            var user = {
                id: value["id"],
                firstName: value["first_name"],
                lastName: value["last_name"],
                email: value["email"],                 
                lat: value["latitude"],                  
                long: value["longitude"]
            };

            var firstName = user.firstName,
                lastName = user.lastName,
                email = user.email,
                userLat = user.lat,
                userLong = user.long;

            // marker
            var markerLatLng = {lat: userLat, lng: userLong};

            var marker = new google.maps.Marker({
                position: markerLatLng,
                map: map
            });


        }); 

    }
});

Am I heading in the right direction, or is there a more efficient method to iterate through all entries and generate markers based on their latitude/longitude coordinates? Your feedback would be greatly appreciated!

Answer №1

There are two issues that need to be addressed in this situation.

The first challenge is converting userLat and userLong into floating point numbers. This can easily be achieved by following the instructions provided in my previous comment:

var markerLatLng = {lat: parseFloat(userLat), lng: parseFloat(userLong)};

The second issue you are encountering is related to the accessibility of your map instance, as it has been defined locally within the initMap function. To resolve this, simply modify the code as shown below:

var map;

function mapInit(){
  map = new google.maps.Map('');
}

These changes should help solve the problem.

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

Utilize JavaScript to extract data from an XML file through a specified

Hello, I am new to JavaScript, Currently, I am working on a project where I need to parse an XML File using JS and jQuery. Could you please advise on how to open an XML file based on its URL? var xml = "File.xml", xmlDoc = $.parseXML( xml ), $xml = $( x ...

Using React hooks to update the state of an array from one component to another

I am currently working on a MERN blog website project and I've encountered an issue while trying to update comments on a post. I'm editing the comment from another component but facing difficulty in updating the state after making changes. Would ...

What is the process for integrating a new token into an established programming language, such as TypeScript?

Utilizing setMonarchTokensProvider allows me to define tokens, but it has limitations. I am able to create a new language or override existing typescript, however, this does not provide me with access to the rest of the typescript tokens that I still requi ...

JavaScript click event not triggering on ASP.NET button

Currently, I am attempting to invoke a C# function from JS without using ajax. One approach I have tried is creating an ASP.NET button that, when clicked, calls the C# function and triggers the click event from JS: In the HTML section: <asp:Button run ...

Could there be any issues with the structure of my mongoose schema?

I've been stuck for 3 hours trying to solve this problem. I can't seem to retrieve any data from my document. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var accountSchema = mongoose.Schema({ username: String ...

I'm having trouble locating my JavaScript files while trying to render a dynamic webpage

My navbar is set up to link to a dynamic web page like this <li class="<%= title == 'Cryptofolio' ? 'navbar-item active' : 'navbar-item' %>"> <a class="nav-link" href="/cryptofolio/< ...

Modify an HTML tag attribute on a webpage with jQuery

I'm attempting to understand the process of developing a basic Chrome extension that modifies a certain tag's property on a webpage. The website contains the following code snippet: <body ondragstart="return false;" onselectstart="return fal ...

Doing AngularJS Controllers Properly

Recently, my colleagues and I have been discussing the optimal approach to creating an AngularJS controller. There are various methods to create one, but my goal is to standardize our team's practices and follow the most effective way. When I refer to ...

my PHP script for scraping does not contain any loops

After creating a code to scrape titles and links from a website, I ran into an issue with the script. The script looks like this: <?php $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_s ...

Is it secure to use console.time() in a Node.js environment?

Looking at a small snippet of node.js code, here's what I have: console.time("queryTime"); doAsyncIOBoundThing(function(err, results) { console.timeEnd("queryTime"); // Process the results... }); Running this on my development system gives m ...

Utilize Javascript to perform operations on ndb.key()

When working with my application, I encounter keys that are created within a Python system and written to Google Datastore. To access the corresponding data, I require the IDs of these items, which are contained in the 'key' string. Unfortunate ...

Is it possible that attaching the click event directly to the ID is effective while attaching it to the childnode is not working

Can anyone help me with a problem I'm having? When I try to target a specific element by accessing its child nodes, the click event doesn't work. However, if I use getElementById and then attach the click event through that method, it works. Idea ...

Struggling to implement server side processing with Datatables in MVC4?

Greetings, our current setup involves an MVC4 application that is handling a large number of records with thumbnail images in a jQuery Datatables driven view. Unfortunately, the loading time is slow due to all thumbnails being fetched at once during a GET ...

Exploring the Power of Laravel 5 with AJAX

When selecting a client name, I would like to use ajax to display a partial form. Currently, I am able to retrieve data from the database with this script: <script> $('#client').change(function(){ var client = $(this).val(); var ...

tips for applying a where clause on a jsonb column in an included table with sequelize

I currently have 2 tables stored in a postgres database. Table_A -------- id BIGINT metadata JSONB Table_B -------- id BIGINT a_id BIGINT metadata JSONB Data Table_A id | metadata 1 | {'gender': 'Male', 'name': 'xyz&ap ...

Creating secure RSA keys using a predetermined seed - a step-by-step guide

Is it possible to utilize a unique set of words as a seed in order to recover a lost private key, similar to how cryptocurrency wallets function? This method can be particularly beneficial for end-to-end encryption among clients, where keys are generated o ...

How can I preload images for smoother navigation on my WordPress AJAX?

I am working with a WordPress site that has ajax navigation. Whenever a user clicks on a link on the left side, the HTML content within <div class="page-details"></div> is loaded. My goal is to preload any images that will be displayed in this ...

Having difficulty creating a popover that is activated by clicking on the three dots, similar to the ones seen in Facebook posts

I have a Django template displaying a list of posts and I want to add three dots to each post. When clicked, a popover should appear with clickable options like Delete and Copy Link. To get a better idea of what I'm looking for, you can reference Inst ...

Integration with the Mastercard MIGS API platform

I am looking to seamlessly integrate the payment portal into my website, allowing users to input their information without being redirected to the MasterCard interface. Here is where they will fill out their details: My Portal https://i.stack.imgur.com/e ...

Is AJAX HTML element swapping a breeze with Rails controllers?

It would be great to have an ERB partial set up like this: <ul id='things-index'> <% @things.each do |t| %> <li><%= t.name %></li> <% end %> </ul> And have the ability to update it in the contro ...