Displaying numerous information panels on Google Maps by extracting data from MySQL

Help needed! I've been struggling with this code for a while now. I can show multiple markers on the map but can't figure out how to display info details in a pop up box when they are clicked. Currently, I'm just trying to make it say "Hey!" as a test. Any suggestions would be greatly appreciated!

<script src="https://maps.googleapis.com/maps/api/js?signed_in=true&callback=initMap"
        async defer>
    </script>
<script type="text/javascript">
        var map;

var image = 'images/marker_blast.png';

 

        function initialize() {
            // Set static latitude, longitude value
            var latlng = new google.maps.LatLng(40.4313684, -79.9805005);
            // Set map options
            var myOptions = {
                zoom: 11,
                center: latlng,
                panControl: true,
                zoomControl: true,
                scaleControl: true,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            // Create map object with options
            map = new google.maps.Map(document.getElementById("map"), myOptions);

//MARK MAP
<?php
$markers = $mysqli->query("SELECT * FROM reports");

while($row_marker = $markers->fetch_assoc()) {

// uncomment the 2 lines below to get real data from the db
// $result = mysql_query("SELECT * FROM parkings");
// while ($row = mysql_fetch_array($result))
echo "addMarker(new google.maps.LatLng(".$row_marker['lat'].", ".$row_marker['lng']."), map);\n";





}
?>


function addMarker(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: image,
size:30,
draggable: false, // enables drag & drop
animation: google.maps.Animation.DROP
});

}

var infowindow = new google.maps.InfoWindow();  
google.maps.event.addListener(marker, 'mouseover', (function(marker) {  
   return function() {  
   var content = "Hey";  
   infowindow.setContent(content);  
   infowindow.open(map, marker);  
   }  
 })(marker));  


</script>

Answer №1

To properly link the InfoWindow to the marker, make sure to include it in the addMarker function at the location where the marker is created:

function addMarker(location, title, map) {
    var marker = new google.maps.Marker({
        position: location,
        map: map,
        icon: customIcon,
        size: 30,
        draggable: false, // allow drag and drop
        animation: google.maps.Animation.DROP
    });
    
    google.maps.event.addListener(marker, 'mouseover', (function (marker) {
        return function () {
            var message = "Hello "+title;
            infowindow.setContent(message);
            infowindow.open(map, marker)
        }
    })(marker));
}

Sample demonstration on JSFiddle

Answer №2

Have you considered restructuring the code to avoid echoing the function inside the while loop? Perhaps a method like this could be more efficient.

<?php foreach($markers as $row_marker) {
    $result = mysqli_query($conn, "SELECT * FROM locations");
    while ($data = mysqli_fetch_array($result)) { ?>

        addLocation(new google.maps.LatLng(<?php echo $row_marker['lat']; ?>, <?php echo $row_marker['lng']; ?>), map);

    <?php } ?>
<?php } ?>

Additionally, it seems that the second while loop is redundant since you're not utilizing the result $data.

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

A method that sorts an array of objects based on their properties

I am currently working with two specific objects: clinics: [ { id: 1, name: 'New Hampshire Veterinarian Clinic', plans: [ 'handle123', 'handle567', ] }, { ...

Verifying Angular (2+?) Compatibility: Opening and Closing Material mat-menu on Hover [GUIDE]

After extensive research, I tried various methods to hover a material menu to display its options. However, the solutions I came across were either too complicated or ineffective. Therefore, I decided to develop my own solution by combining elements of e ...

Dealing with errors in AngularJS factory servicesTips for managing errors that occur

Factory code app.factory('abcFactory', function ($http, Config, $log) { var serviceURL = Config.baseURL + '/results'; return{ results:function() { var promise = $http({ method: 'GET&apos ...

What could be causing the lack of updates in my shared service across all components?

I have implemented an Angular2 app where I am initializing an authentication service called LocalStorage which I want to be accessible across all my components: bootstrap(AppComponent, [ ROUTER_PROVIDERS, LocalStorage ]); The definition of the Lo ...

Retrieving components of an array

I am looking to extract elements from an array, then store them in a new array and compare them to another array. The challenge is that I do not want to extract the elements in a specific order. I have tried using the .slice function for extracting element ...

How can I modify the appearance of the bootstrap scrollbar with scrollspy?

I'm struggling to modify the color of the scrollbar in Bootstrap scrollspy despite having a functional scrollbar. Here is an example of my code: HTML: <body> <div class="container, scrollbar" id="myScrollspy"> <div class=" ...

Having trouble with the HTML5 canvas for loop not rendering the initial object in the array?

Essentially, I'm attempting to iterate through each letter in a text string (specifically the text "marius"). However, there's an issue where the first letter is not being displayed. When the text is "marius", only "arius" is drawn. I've exh ...

I am facing issues with jQuery's live and livequery functions when trying to use them with a form that is being loaded dynamically through

Previously, I inquired about a related issue regarding attaching behavior to an element with jQuery after insertion. However, I have not yet found a solution. For clarity's sake, I am posing a new question with a different scenario. Below is the code ...

Encountering an issue with JQuery when attempting to create a double dropdown SelectList. Upon submitting the POST request, the output received is always

Two dropdownlists have been created, where one acts as a filter for the other. When selecting a customer from the dropdown Customer, only a limited set of ClientUsers is displayed in the dropdown ClientUser. This functionality is achieved using a jQuery fu ...

Unraveling the Mystery of Passing Props in React.js

Currently taking an online course to learn React, I encountered a unique scenario where one property is attached to another property in this manner: this.props.property01(this.props.property02) The tutor briefly touched on this code line, leaving me quit ...

Optimizing Backend Access with Laravel and Vue JS: How to Choose the Most Effective Approach

Currently, I am utilizing Laravel API passport to handle authentication in my Single Page Application (SPA) built with Vue. At the moment, whenever I need to access the backend server, I have to include a header in order to be allowed through the protected ...

Utilizing inputRef in conjunction with MUI's useAutocomplete

Is there a way to pass the "inputRef" to Material UI's useAutocomplete? I'm looking to set a custom reference on the input, but the getInputProps() method from useAutocomplete already requires its own reference. I've attempted various appr ...

AngularJS - Issue with retrieving the most recent entry during $routeChangeStart event

I am utilizing the $routeChangeStart function to redirect authorized users to specific URLs and prevent unauthorized access to special pages. In addition, I have dynamically generated pages that can be accessed via their unique page slugs. To achieve this ...

conceal a division beneath a YouTube video frame upon clicking

I need to hide the 'div .blind' element when a YouTube video (inside 'div #player') is clicked. How can I achieve this? Here's an example: JS: ... var player; function onYouTubeIframeAPIReady() { player = new YT.Player('pl ...

Express Module Paths Failing to Function Properly

When I first started building my routes, I had everything in one api.js file. However, I realized there might be a better approach, so I did some research online to see how others handle it. After following a few tutorials, I decided on a new layout with s ...

How is it that the identical group is unable to produce an accurate line chart and its corresponding range chart?

Check out my code snippet on JSFiddle here: https://jsfiddle.net/8yf7j3k6/11/ I am currently working on replicating a similar visualization of my data for a range chart, allowing me to scrub through the chart while utilizing tooltips in the line chart rep ...

Exploring Handlebars.js: Understanding the Scope of Global Contexts

If I have a static list of cached users within my application under App.Users, there will likely be various instances where I need to display the list of users. Typically, I would just pass the list along with the context to the template. var tmpl = Handl ...

When working with JavaScript, it's important to note that any reference used outside of the catch block

Our JavaScript code includes a try...catch block that functions as follows: We import the customFile using: const ourCustomClassFile = require('./customFile'); In the customFile.js file, we have defined a function const sendErrorNotification ...

The system is unable to interpret the symbol property 'Symbol(Symbol.iterator)' because it is not defined

I have created a custom .any() method for Array objects to loop through an array and check if any item passes a specified function: Array.prototype.any = (comparator) => { for(let item of this){ if(comparator(item)){ return true ...

The initial axios GET request fails to retrieve data upon the first click

Having trouble retrieving data with button click. The issue is that the data is not fetched when clicking the button for the first time, but works fine on the second click. Here's the code snippet: const learnMores = document.querySelectorAll('. ...