Challenges arise when attempting to pass array data from Ajax to Google Maps

I'm facing an issue with my Google map. I have a data array that is dynamically returned, and I want to use it to add markers to the map. However, the markers don't work when I pass the data variable to the add_markers() function. It only works if I directly input the data into the function. Why is this happening and how can I resolve it?

    function RelatedLocationAjax() {
           var lat = $( "#lat" ).val();
           var lng = $( "#lng" ).val();
           var srv = $( "#ServiceId" ).val();
            var data = [
                ["john","Do this service 1 <a href=''>more</a>",  "29.957051,30.914529", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
                ["peter", "Do this service 1 <a href=''>more</a>", "29.956051,30.913529", "http://maps.google.com/mapfiles/ms/icons/green.png"],
                ["sara","Do this service 1 <a href=''>more</a>","29.955051,30.912529", "http://maps.google.com/mapfiles/ms/icons/red.png"],
            ];
            $.ajax({
                type: "POST",
                url: "<?= base_url() ?>services/closest_locations",
                data:"data="+ '{ "latitude":"'+ lat+'", "longitude": "'+lng+'", "ServiceId": "'+srv+'" }',
                success:function(response) {
// When passing the data array to add_markers, it doesn't work
                    add_markers(response);
                }
            });
        }

        function add_markers(data){
        var marker, i;
        var bounds = new google.maps.LatLngBounds();
        var infowindow = new google.maps.InfoWindow();

        document.getElementById('info').innerHTML = "found " + data.length + " data<br>";
        for (i = 0; i < data.length; i++) {
            var coordStr = data[i][2];
            var coords = coordStr.split(",");
            var pt = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
            bounds.extend(pt);
            marker = new google.maps.Marker({
                position: pt,
                map: map,
                icon: data[i][3],
                address: data[i][1],
                title: data[i][0],
                html: data[i][0] + "<br>" + data[i][1]
            });
            markers.push(marker);
            google.maps.event.addListener(marker, 'click', (function (marker, i) {
                return function () {infowindow.setContent(marker.html); 
                    infowindow.open(map, marker);
                }
            })
            (marker, i));
        }
        map.fitBounds(bounds);
    }

Answer №1

Due to the information being returned from the ajax call not being in array form, but rather a response Object.

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

What is the best way to enable and disable the edit-in-place feature using jQuery?

Recently, I decided to experiment with the jQuery In Place Editor but I've come across an issue I can't seem to solve. Below is the code snippet that I have been working on. In my implementation, I am utilizing the jQuery toggle method to enable ...

Unable to modify the model of the directive

I'm facing an issue where additional elements added to my array within a controller of a directive are not being displayed in the view. What's even more frustrating is that when I print my model, it doesn't reflect the new elements that have ...

What is the best way to showcase a collection of data retrieved in JSON format from a server using Ajax

Struggling with sending a request to a PHP file that returns JSON data and facing issues where only one record is displayed with undefined values. Here is the JSON response received from core/backend/comm.php: { "name": "Rehan", "location": "Pune ...

The only numbers that can be typed using Typescript are odd numbers

I am looking for a way to create a type in Typescript that can check if a value is an odd number. I have searched for solutions, but all I find are hardcoded options like odds: 1 | 3 | 5 | 7 | 9. Is there a dynamic approach to achieve this using only Types ...

Using Firefox to cache Ajax calls after navigating back in the browsing history

Currently, I am utilizing an ajax call to invoke a php script that waits for 40 seconds using sleep and then generates the output RELOAD. Subsequently, in JavaScript, the generated output is validated to be RELOAD, following which the call commences again. ...

Adding elements within a loop using jquery

I am currently working on adding a toggle button using Javascript. I want to include three span tags inside it as well. To achieve this, I am creating a span variable and attempting to append it within a basic FOR loop that iterates 3 times. Below is the ...

Tips on making the form validation script operational

After developing a form alongside a form validation script to ensure that all fields are completed, the name and city sections only contain letters, while the age and phone sections solely include numbers, issues have arisen. It seems that despite the cons ...

Experiencing difficulty navigating JSON objects

I am facing an issue with a JSON structure that has the following format: [ { "coordinates": [ 75.71027043, 26.88661823 ] }, { "coordinates": [ 75.71027043, 26.88661823 ...

jQuery AJAX call: The specified endpoint was not found

Utilizing jQuery, I am fetching a JSON package to update my display. In an effort to implement global ajax handlers for a universal "AJAX failed" handler, I encountered an issue. Even when I halt the back end (ASP.NET), the request does not technically "fa ...

Concern raised about the challenge of removing an element from an array and its potential

When attempting to remove an element from an array without altering the state, I typically use the following code snippet: const tempArray = [ ...originalArray ]; tempArray.splice(index, 1); setOriginalArray(tempArray); After some experimentation, I deci ...

Visual Studio - TypeScript project synchronization issue

Currently using the 2015 version of Visual Studio Community, I am facing an issue while working on a typescript project. Whenever I make modifications to the code, debug it, and save it using ctrl + s followed by refreshing the browser with ctrl + r, the c ...

Flickering transitions in Phonegap and jQuery Mobile pages

As a beginner in Phonegap/jQuery Mobile, I have encountered a frustrating issue of a white screen appearing during page transitions. Despite trying various solutions found online, such as using -webkit-backface-visibility:hidden;, the problem persists. I ...

What steps can I take to ensure the reset button in JavaScript functions properly?

Look at this code snippet: let animalSound = document.getElementById("animalSound"); Reset button functionality: let resetButton = document.querySelector("#reset"); When the reset button is clicked, my console displays null: resetButton.addEvent ...

Retrieving and showing information from a database (Using Javascript Ajax)

I'm in need of assistance with a project for my course and would appreciate any guidance or help that can be offered. My task involves creating a simple JavaScript XML Http Request to display basic information (specifically the country_name & country_ ...

Meta tag information from Next.js not displaying properly on social media posts

After implementing meta tags using Next.js's built-in Head component, I encountered an issue where the meta tag details were not showing when sharing my link on Facebook. Below is the code snippet I used: I included the following meta tags in my inde ...

Focus on a primary window

When a new window is opened using the target attribute of _blank, is it possible to target links to open in the original "parent" window? Appreciate your help! ...

Blank YouTube Popup Modal

I am in the process of creating a pop-up modal that contains an embedded YouTube video, but my modal is not displaying properly. I am utilizing Bootstrap and have two separate sections along with JavaScript code. When the modal appears, it remains empty. I ...

What is the best way to retrieve all string constants from HTML or JSX code?

UPDATE: I recently developed my own babel plugin CLI tool named i18nize-react :D I am currently in the process of translating an existing react application from English to another language. The string constants in the JSX are all hardcoded. Is there a sim ...

Frozen Blanket: Modifying Particle Velocity

I need assistance adjusting the particle speed in this snowfall animation script. I'm having trouble locating the specific values that control the "Falling Speed." The current speed of the falling particles is too fast, and here is most of the code sn ...

Problem arises when attempting to slice an array that is defined in the parent component

Seems like a simple mistake, but here's what happened: In the main parent component, I have an array defined: ... <object-list-grid v-bind:objects="objectsList" ></object-list-grid> ... data() { return { ... ...