0
votes

I have an issue which has been causing me a headache for a few days and is probably a really simple fix for somebody with a bit more knowledge around json data than me. So hopefully somebody can help.

Firstly, I am using scriptcase, although this shouldn't matter as I am using a blank application and the only scriptcase macro I am utilising in my code is a database lookup, as you will see.

I am essentially selecting multiple fields from the database, preparing them using json to be placed inside a function for a Google Maps API (latitude and longitude, firstname and surname for description). It works perfectly, however throughout the generated array, it automatically places a comma at the end of every line. I cannot get my head around how to remove this. I have tried rtrim and trim, and neither work, but they do take the value right off of the end of the whole result, if that makes sense?

Apologies in advance if this is incredibly simple!

My code looks like this:

$LatLong = array();
$i = 0;
$llresult = '';

sc_lookup(ds,"SELECT latitude,longitude,first_name,surname FROM staff WHERE active=1");

for($i=0;$i<count({ds});$i++){
    $LatLong[0][] = "var Marker = new google.maps.Marker({ position: {lat: ". {ds[$i][0]} .", lng: ". {ds[$i][1]} ."}, map: map, title: '". {ds[$i][2]} ." ". {ds[$i][3]} ."' });";
}



//include $result data
$llresult = json_encode($LatLong);


//$result treatment
$llresult = str_replace("[[","", $llresult);
$llresult = str_replace("]]","", $llresult);
$llresult = str_replace('"','', $llresult);

?>

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Locations</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 90%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>

    function initMap() {
        var myLatLng = {lat: 37.3320045, lng: -122.0329699};

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 12,
            center: myLatLng
        });

        <?php echo $llresult; ?>

    }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap">
    </script>
  </body>
</html>

<?php

I should have added that my output upon echoing the $llresult is showing as the following:

var Marker = new google.maps.Marker({ position: {lat: 37.3320045, lng: -122.0329699}, map: map, title: 'Joe Bloggs' });,var Marker = new google.maps.Marker({ position: {lat: 37.3320045, lng: -122.0329699}, map: map, title: 'Jane Doe' });

1
Your approach is incorrect. Javascript codes must be in Javascript. - u_mulder
you may want to consider adding your markers using the geojson function - happymacarts
And in the end you will overwrite your var Marker as many times as there are items in array. - u_mulder
@u_mulder is correect unless you were to append you iterator to the var name you will continue to overwrite it $LatLong[0][] = "var Marker$i = new google.maps..." - happymacarts
Why do you need to json_encode? It seems that you are only writting javascript code. - Felippe Duarte

1 Answers

3
votes

A simple approach that divides code and data is:

$LatLong = array();
$i = 0;

sc_lookup(ds,"SELECT latitude,longitude,first_name,surname FROM staff WHERE active=1");

for($i=0;$i<count({ds});$i++){
    $LatLong[] = [
       'lat' => $ds[$i][0],
       'lng' => $ds[$i][1],
       'title' => $ds[$i][2] . " ". $ds[$i][3]
    ];
}

So, now in $LatLong you will store coordinates and titles. Now, to javascript:

var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: myLatLng
});

var latLong = <?php echo json_encode($LatLong)?>;
// iterate over latLong and create markers:
for (var key in latLong) {
    new google.maps.Marker({ 
        position: {lat: latLong[key]['lat'], lng: latLong[key]['lng']}, 
        map: map, 
        title: latLong[key]['title']
    });
}