The markers on Google Maps that are being loaded through Ajax are not appearing as expected

Everything seems to be working perfectly with my Google Map - the centering feature is smooth and accurate. However, I'm facing an issue when trying to add markers without reloading the entire map. Unfortunately, no visible markers appear on the map.

Here's a glimpse of my script:

function initializeMap(){
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(48.2136522, 16.386172),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    var infowindow = new google.maps.InfoWindow();
}

function addMarkerToMap(locations){
        var marker, i;

        for (i = 0; i < locations.length; i++) {  
          marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map,
            visible: true
          });

          google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
              infowindow.setContent(locations[i][0]);
              infowindow.open(map, marker);
            }
          })(marker, i));
        }
}

The crucial part of my ajax request looks like this:

...
      success:function(data){
        $('#pagination_content table').empty();
        data = $.parseJSON(data);

        i = 1;
        coordinates = "";
        for(var i in data.results) {
        $('#content_table').append("blablabla");
        coordinates += "['" + data.results[i].title + "', " + data.results[i].lat + ", " + data.results[i].lat + ", " + i++ + "], ";
        };

        coordinates = coordinates.slice(0, -2)
        addMarkerToMap(coordinates);
      },
...

The output of coordinates appears as follows:

['abc', 48.1857442, 48.1857442, 0], ['xyz', 48.2136522, 48.2136522, 1]

The initializeMap function is triggered by the document.ready() event.

I am utilizing API v3 for this implementation.

Answer №1

When working with the coordinates, you first slice them and then convert them into an array by using var locations = [ coordinates ];.

I find this process a bit confusing. Since slice already returns an array, why create another array? Have you made sure that your loop is functioning properly?

Consider removing var locations = [ coordinates ]; from g_maps_marker and running it again to see if it works correctly.

** Edit **

Upon further examination of the code, I noticed that you are attempting to use a string that resembles an array in your loop. This approach will not yield the desired results.

For instance:

latitude twice instead of including longitude. I have rectified this issue in my revised code.

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

Using AngularJS for AJAX operations with dynamic PHP variables

I have an AngularJS code that is looping through an AJAX JSON response like this: <div ng-repeat="post in posts"> {{post.title}} {{post.url}} </div> It's working fine. How can I pass a PHP variable based on the JSON? Let's assume t ...

Using Symbol.iterator in Typescript: A step-by-step guide

I have decided to upgrade my old React JavaScript app to React Typescript. While trying to reuse some code that worked perfectly fine in the old app, I encountered errors in TS - this is also my first time using TS. The data type I am exporting is as foll ...

Convert an object into a tree structure for TreeTable, grouping by two levels in Typescript or JavaScript

I am currently working on transforming a list into a tree structure suitable for a PrimeNG TreeTable. [{pk:"1", corpID:"1234", date: "31/03/21", rela:"4325", price:"20.00"}, {pk:"2", corpID:" ...

Having trouble selecting a default option in a dynamically populated select dropdown using ng-model in the dropdown

For my Angularjs application, I needed to dynamically return a select drop down with its selected option. To accomplish this, I implemented the following function: function getCellRendererMapping(data) { if (data.order == 6) { return funct ...

Struggling to figure out why jqueryrotate isn't functioning as expected

I'm having trouble getting example #2 of jqueryrotate from this page to work on a simple HTML page. Can someone help me figure out what I'm doing wrong? Thanks! Here is the code I'm using: <!DOCTYPE html> <head> <script typ ...

Unable to manage the rotation in Three.js GLTFLoader

Issue Why am I unable to rotate the angle of an object? (scene.rotation.x += 0.03;) The camera can, but the scene object cannot. I've searched for a solution for a long time without success. Here is my code: import * as THREE from 'https://un ...

Tips for displaying an array of objects in a single <li> tag in React

I have an array with nested arrays structured like this: [Array(2), Array(2), ...] example Each subarray contains two objects with a "text" property. obj = {key: something, text: something} Now I am looking to render the "text" property of each subarra ...

Configure vue.config.js to generate distinct pages based on different environments

Currently, I am utilizing Vue with webpack to construct a Multi-Page Application and have the following setup: pages: { index: { entry: ... template: ... ... } page1: { entry: ... template: ... ... } } I am looking to add a deb ...

Loading content dynamically on a Plone page using AJAX

I am currently working on a website built with Plone, but I have encountered an issue. I want to load specific content from a template using an ajax call on a regular Plone page triggered by an event. Do I need to create a Python script for this? If so, wh ...

Vue Method always executed (regardless of click event)

I'm fairly new to vue and still getting a grasp on the fundamentals of my code. Currently, I am facing an issue with a Method. It should only trigger when the user clicks on the button, but it seems to be triggered all the time. I even tried adding ...

Using a JSON string with form field names and corresponding values to automatically fill in form fields using jQuery

My JSON string looks like this: [{"meta_key":"algemeen_reden","meta_value":"oplevering"},{"meta_key":"algemeen_netspanning","meta_value":"230"}] Currently, I am using the following script to fill out form fields: // Grab Algemeen Data get_algemeen_data ...

Can you explain the contrast between the functions 'remove' and 'removeChild' in JavaScript?

I have recently coded an HTML page in order to gain a better understanding of how element removal functions. Code: <html> <head> <script> var childDiv = null; var parent1 = null; var parent2 = null; function ...

Create a new variable to activate a function within the parent component in Vue

I want to invoke a function in the parent component from its child component. In my Vue project, I have designed a reusable component that can be used across multiple pages. After the function is executed in this component, I aim to call a specific functi ...

JavaScript and HTML are commonly used programming languages for developing

By utilizing JavaScript, I was able to generate a table dynamically based on user input. For example, if the user enters 3 and clicks "go", a table with 3 rows is created. Using the .keyup function allowed me to target a column successfully. However, an i ...

Unable to locate the accurate information

Every time I run the cycle, there should be a match with the specified parameters and the message "OK" should appear. However, I am always getting a result of "No". request( { url: 'http://localhost:5000/positions/get', metho ...

The functionality of Webdriver.waitUntil is not meeting the expected outcomes

I'm currently utilizing webdriverio version 4.5: ./node_modules/.bin/wdio -v v4.5.2 In my scenario, I am in need of waiting for the existence of a specific element and handling the situation if it doesn't exist. Here is an example code snippet ...

Safari and Chrome are directing Angular Http Post requests to different URLs

Using the Angular framework and the $http directive to make a post request to our API endpoint works fine in Chrome, but I'm encountering an issue in Safari. Below is the code snippet from my Api factory: assignments: function(csv) { var deferred = ...

Oops! We encountered an internal server error while trying to resolve the import for "@vue/server-renderer"

Several months ago, I created a Vue 3 project using Vite and everything was running smoothly. However, today when I tried to make a small modification, an error occurred at runtime. All Vue files are showing the same error message: [vite] Internal server ...

AngularJS and Spring Rest team up for seamless drag-and-drop file uploads

I have successfully implemented file upload using AngularJS and Spring REST, but now I want to change it to use dropzone.js or any other drag and drop file upload method. I tried using the dropzone.js library, but I am facing issues integrating it with Ang ...

Enable automatic profile login for the Firebase application

Imagine a web application created using Vue and Firebase. The main query revolves around automatically logging into the app after page reload, particularly accessing the database post authorization. Following user authentication, crucial data such as email ...