-4

I am having a hard tme doing this and I tried many attempts but it still won't work. I need to put the name, latitude and longitude in the var = locations[];

The purpose of this code is to show the locations of the places in a 2D Map

<div id="map" style="width: 1150px; height: 500px;"></div>

<?php  
require 'dp.php';
$db = new DB();

$records = $db->shop_locat();
if(isset($records)) {
    foreach($records as $row) {
        echo '<script type="text/javascript"> var locations = [ ';
        echo ' [ '.$row['name'].' , '.$row['lat'].', '.$row['lng'].' ]; </script> ';
    }
}
?>

<script type="text/javascript">
// The original code... var locations = [['Vista Mall Bataan', 14.655008481768526, 120.5338206800952],];

var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10.5,
    center: new google.maps.LatLng(14.6417, 120.4818),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});
        
var infowindow = new google.maps.InfoWindow();
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});
          
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
            infowindow.setContent(locations[i][0]);
            infowindow.open(map, marker);
        }
    })(marker, i));
}
</script>

dp.php

// Get Coordinates
    public function shop_locat() {
        $qstr = "SELECT * FROM tbl_location";
        $result = mysqli_query($this->link, $qstr);
        $records = array();

        if (mysqli_num_rows($result) > 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                $records[] = [
                    'lat' => $row['lat'],
                    'lng' => $row['lng'],
                    'name' => $row['name'],
                    
                    
                ];
            }
        } else {
            $records = null;
        }
        mysqli_free_result($result);
        return $records;
    }

I tried multiple variations of but it still won't work. So I am hoping that someone can help me.

This is the output that I want, but the name, latitude, and longitude is like this:

var locations = [['Vista Mall Bataan', 14.655008481768526, 120.5338206800952],];

The name, latitude, and longitude of the place is in my phpmyadmin, but when I try to get it, using my code above, there is no output

Patrick Janser
  • 3,318
  • 1
  • 16
  • 18
  • 3
    Tip: Use json_encode to generate valid JS/JSON objects which you can then embed in your JS output from PHP. Much simpler, easier to read, maintainble and more reliable than concatenating it all by hand as you're doing now. – ADyson Jun 08 '23 at 12:38
  • 1
    Anyway, what does "won't work" mean exactly? Are you not getting the output you expect? Is there an error? Some other unexpected behaviour? You'll need to be much more specific before we can provide meaningful help. See also [ask]. Thanks. – ADyson Jun 08 '23 at 12:39
  • 1
    When you examine the resulting client-side code generated by this server-side code, what is it and how does it differ from what you expect? – David Jun 08 '23 at 12:40
  • 3
    My main observation would be that inside `foreach($records as $row) {` you are making a new script each time it loops, and a new copy of the `locations` variable. This will get output to the browser as many times as the foreach loop runs. Clearly, you cannot have multiple variables of the same name, they will just overwrite each other. So maybe that's (part of) the issue? Did you actually want locations to be a single array contaning multiple other arrays, perhaps? – ADyson Jun 08 '23 at 12:41
  • `This is the output that I want`. ok thanks. That's one of the things we asked for. The other aspect was: what are you getting instead? – ADyson Jun 08 '23 at 12:54
  • There is no map, literally none. Also, I apologize for stating my situation earlier, which didn't get specific. I appreciate the help – Marc Jacob Jun 08 '23 at 12:57
  • _Small additional point_ [Script tag: type or language (or omit both)?](https://stackoverflow.com/questions/2267476/html-script-tag-type-or-language-or-omit-both) – RiggsFolly Jun 08 '23 at 13:03
  • 2
    As ADyson mentionned, your foreach loop to create the JavaScript isn't correct. Best to prepare the array in PHP and then convert it to JavaScript with [json_encode()](https://www.php.net/manual/en/function.json-encode.php). The script tag and the variable should only exist once in the HTML. I see that CodeThing just gave you the answer in code :-) – Patrick Janser Jun 08 '23 at 13:05
  • `There is no map, literally none`...that's just a surface symptom. David asked you to describe the resulting client-side code your PHP generated. As I suspected, you were duplicating the locations object. Inspecting the generated code (e.g. using your browser's Developer Tools, or the View Source feature) would have allowed you to see that quite easily. – ADyson Jun 08 '23 at 13:20

1 Answers1

2

You can build your array in the required format and json encode it so that you can put that in the javascript. Buliding the array manually by hand is error prone.

You can try something like below.

<?php
$locations = array();
if(isset($records)) {
    foreach($records as $row) {
        array_push($locations, array($row['name'], $row['lat'], $row['lng']));
    }
}

echo '<script type="text/javascript">';
echo 'var locations = '.json_encode($locations).';';
echo '</script>';
?>
CodeThing
  • 2,580
  • 2
  • 12
  • 25
  • 2
    To make it even cleaner (and get the benefit of your IDE's syntax highlighting on all the code), you can close PHP: `?> – M. Eriksson Jun 08 '23 at 13:07
  • Good idea @M.Eriksson :-) But will JS linters complain on the PHP code injected in the JS? – Patrick Janser Jun 08 '23 at 13:11
  • This code worked! Thank you so much for the help! – Marc Jacob Jun 08 '23 at 13:12
  • _"But will JS linters complain on the PHP code injected in the JS?"_ - I honestly don't know. I've never used JS linters on HTML or PHP files. If you're mixing HML/PHP/JS on the same page (the source code, that is), I doubt you're using a linter. If you're using some in your IDE, it should be smart enough to know what to look at. – M. Eriksson Jun 08 '23 at 13:13