Trouble with Multiple Google Maps in Bootstrap Modal

I'm currently working on a website that has the capability to display users' locations and generate maps based on their coordinates. I have successfully implemented the functionality for showing a single user's location on the map using modal, however, when trying to display multiple user data from the database, the map fails to show up. I've been struggling to identify the root cause of this issue, so any assistance would be highly appreciated. Below is a snippet of the code I am working with:

while($u=mysqli_fetch_array($query)){
//$coordinate format from database is 123.456,789.876
$latlng = explode(",",$coordinate);
$lat = $latlng[0];
$lng = $latlng[1];
echo "
<tr>
    <td>
    <script src='https://maps.googleapis.com/maps/api/js?callback=init$modal'></script>
    <script type='text/javascript'> 
        function init$modal() {
          var map$modal;
          var latlng$modal = {lat: $lat, lng: $lng};
          var myOptions = {
                zoom: 16,
                center: latlng$modal,
                mapTypeId: google.maps.MapTypeId.ROADMAP
          }
          map$modal = new google.maps.Map(document.getElementById('map_canvas$modal'),myOptions);

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


          $('#myModal$modal').on('shown.bs.modal', function(e) {
              google.maps.event.trigger(map, 'resize');
              return map.setCenter(latlng$modal);
          });
        }
    </script>
    <div class='modal fade' id='myModal$modal' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>
      <div class='modal-dialog'>
        <div class='modal-content'>
          <div class='modal-header'>
            <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>
          </div>
          <div class='modal-body datauser'>
            <table class='table'>
                <tr>
                    <td style='vertical-align: top;'>
                        <div class='mapcaller' id='map_canvas$modal' style='width:100%; height:250px;'></div>
                    </td>
                </tr>
            </table>
          </div>
        </div>
      </div>
    </div>

    <button type='button' data-toggle='modal' data-target='#myModal$modal' class='btn btn-default btn-sm' style='float: right; margin-right: 5px; margin-left: 5px;'>
      <i class='fa fa-info-circle'></i> See data
    </button>
    </td>
</tr>";
$modal+=1;

Incorporating bootstrap's modal, each map is nested within a loop inside the modal structure. Your insights and suggestions are greatly valued.

Answer №1

Sorry, that approach won't be effective. It's important to avoid defining javascript functions within a php loop as it can cause complications.

Instead, create an init() function and simply echo it without embedding php variables. Use the while-loop to generate an array of data which you can then pass to the function.

Consider implementing the following method:

<?php
$locations = array();
while($item = mysqli_fetch_array($query)) {
  $coordinates = explode(",", $item);
  $locations[] = array('lat'=>$coordinates[0], 'lng'=>$coordinates[1]);
}
$locations_json = json_encode($locations);  
echo '<script>
  var locations = ' . $locations_json . ';
</script>';
?>
<script>
function init() {
  // Your code here.
}
// Additional code goes here.
</script>

I'm not sure about modal functionality, but I recommend avoiding php (or any other) variables within javascript functions.

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 am looking for a string with this particular format in JavaScript

I am working with a JSON string array that looks like this: var dataMaster = [ {"id":1,"name":"John Doe","age":30}, {"id":2,"name":"Jane Smith","age":28} ] If you want to see how I would like to transform this data, please visit the following lin ...

What could be the reason for the unexpected undefined value of my ajaxurl variable?

Seeking assistance with implementing code to track mp3 plays in a Wordpress plugin using ajax-counter.js jQuery(document).ready(function($) { console.log(ChurchAdminAjax.ajaxurl); $("audio").bind("play", function(){ console.log(ChurchAdmin ...

Adjusting the line-height in CSS dynamically based on the length of characters using jQuery

I am facing an issue with the Twitter widget on my website where our company's latest tweet sometimes gets cut off if it exceeds a certain length. I want to dynamically adjust the line-height CSS property of the element based on the tweet's chara ...

Enhance your Rails application by dynamically updating table cells with Ajax, eliminating the need for

In my index.html.erb file, I have set up one form and one table. Using Ajax allows me to submit the form without any redirects. <%= form_for approval, remote: true do |f| %> <%= f.check_box :pass %> <%= f.submit%> <% end %> My ...

I am encountering problems with converting Array to JSON format in PHP for utilization in Javascript

I always face challenges when it comes to converting Array into JSON format. Currently, I am utilizing a selectbox plugin developed by TexoTela. For this plugin to work, it requires a specific JSON structure as shown below: { "ajax1": "AJAX option 1 ...

Setting a default value for a prop function in VueJS

How can a default function be set for a prop with the type of function? props: { clickFunction: { type: 'Function' default: ???? } } ...

Check if the <ion-content> in Angular Ionic has reached the bottom when scrolling

I'm in the process of developing a messaging app using Angular and Ionic. I want to trigger the scrollToBottom method only when it is scrolled to the very bottom. This way, if someone scrolls to the top to read old messages while their partner sends a ...

The React component fails to render on the screen

Upon retrieving data from the database server, attempts to render it result in the data being shown in the console log but not displayed in the component. What could be causing this issue? useEffect(() => { readRequest().then(setTodos); c ...

Error encountered during npm Windows update

Recently, I encountered an issue while trying to update npm on Windows. I came across a helpful post on Stack Overflow that suggested running the following commands: Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force npm install -g npm-windows-upg ...

Increase the value of a property within an array of objects based on certain conditions

My task involves incrementing the rank value by one until the name property changes. I am utilizing the page and rank properties to track when this change occurs. In addition, I want to increment it once whenever the type is not equal to none, and then re ...

Sort by characteristics of embedded array - Knockout

I'm struggling with filtering a nested array using Knockout. My goal is to filter the array by both 'tag-names' and 'name'. For example, searching for 'whal' should display all objects that contain a tag with that name ...

Concealing an Automatically Updated Section when Devoid of Content -- Ruby on Rails Version 4

I have come across various solutions to this problem, but none of them seem to be effective for my specific project. In my application, the user's previous choices are displayed in multiple divs. Initially, all the divs are empty. As the user progress ...

How can I display a nested dropdown list within a form using JSON data in React?

Utilizing material ui and formik, I have integrated a form that requires a selection box with nested options to be displayed as shown in the image linked here. (The value selected needs to be submitted upon form submission) https://i.sstatic.net/02AI2.png ...

NestJS - The GraphQL schema was expected to be defined, but was found to be

I've been working on setting up a small GraphQL API using NestJS 8. I made sure to install all the required dependencies as per the documentation. However, upon starting the server, I am encountering this error: [Nest] 22727 - 10/30/2021, 10:11:10 AM ...

Maintain the active accordion tab even after navigating away from the page and returning

I am working with an accordion that contains links to subpages within the tabs' content. I want to ensure that when a user navigates back from a subpage to the homepage, either via the browser's back arrow or a homepage link on the subpage, the t ...

Language translation API specifically designed to convert text content excluding any HTML formatting

I have a dilemma with translating text content in an HTML file into multiple languages based on user input. To accomplish this, I am utilizing the Microsoft Translator AJAX interface. The structure of my HTML file looks something like this; <h1>< ...

Looking to convert files like text or images into binary format using Node.js?

I'm struggling to find a solution for converting any type of file (text, image, etc) into binary format using Node. Can anyone provide some guidance on how to accomplish this task? ...

How do I utilize the file handler to execute the flush method within the Deno log module using Typescript?

I'm having trouble accessing the fileHandler object from my logger in order to flush the buffer to the file. This is the program I am working with: import * as log from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_emai ...

Troubleshooting Azure typescript function: Entry point for function cannot be determined

project structure: <root-directory> ├── README.md ├── dist ├── bin ├── dependencies ├── host.json ├── local.settings.json ├── node_modules ├── package-lock.json ├── package.json ├── sealwork ...

JavaScript Code: Empty a text box when a different one is active

Looking for a solution to clear the content of one textbox when the user interacts with another in HTML and JavaScript. <input id="tb1" type="text" name="textbox1"> <input id="tb2" type="text" name="textbox2"> Seeking JavaScript code that wil ...