1

I have a while loop in php which loops through a file and get three variables for each three lines. Then I use these three variables to create a marker using javascript. It does not work when I pass the php variables in my javascript code. I read related threads(Can I write PHP inside JavaScript inside PHP?) and did modification correspondingly, but it still didn't work.

<?php 
     $n="file.txt";
     $f=fopen($n,'a');
     while(($line = fgets($f)) !== false) {
         $m = $line;
         $long = fgets($f);
         $lat = fgets($f);  
         echo "
            <script type="text/javascript">
                var my_message = '$m';
                var my_long = '$long';
                var my_lat = '$lat';
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(my_lat,my_long),
                    map: map,
                });
            </script>";
    }  
?>

Following is the .php file:

    <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Hi!</title>
<style>
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  #map {
    width: 1000px;
    height: 600px;
  }
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
</head>
<body>
<?php
      $m = $_POST['message'].PHP_EOL;
      $long = $_POST['longitude'].PHP_EOL;
      $lat = $_POST['latitude'].PHP_EOL;

      $n="file.txt";
      $f=fopen($n,'a');
      if ($m !== PHP_EOL) {    // Message is not empty
          fwrite($f,$m);
          fwrite($f,$long);
          fwrite($f,$lat);
      }
      fclose($f);
?>
<script type="text/javascript">
    var map;
    google.maps.event.addDomListener(window, 'load', function (event) {
      navigator.geolocation.getCurrentPosition(function (location) {
          initialize(location.coords.latitude, location.coords.longitude);
      });
    });
    function initialize(Lat, Long) {
      var mapOptions = {
          center: new google.maps.LatLng(Lat, Long),
          zoom: 13,
          mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      map = new google.maps.Map(document.getElementById('map'), mapOptions);
      var myLatLng = {lat: Lat, lng: Long};
      var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
      });
    }
</script>
<div id="map"></div>
 // Following are buggy code.
<?php 
     $n="file.txt";
     $f=fopen($n,'a');
     while(($line = fgets($f)) !== false) {
         $m = $line;
         $long = fgets($f);
         $lat = fgets($f);  
         echo "
            <script type="text/javascript">
                var my_message = '$m';
                var my_long = '$long';
                var my_lat = '$lat';
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(my_lat,my_long),
                    map: map,
                });
            </script>";
    }  
?>
</body>
</html>

Here is my file.txt

Hello!
151.2069900
-33.8674870
I am here!
-80.56344
43.471536666666665
I was here before!
48.8566140
2.3522220
I will come here one day!
22.851563
-79.278140
Community
  • 1
  • 1
ZigZagZebra
  • 1,349
  • 3
  • 14
  • 25

1 Answers1

1

You can perform that by counting lines until three times before output

Fixes

change your quotes on type attribute (simple quotes) or you php break on invalid syntax

Use file() return whole file into an array of lines

How to

THE BAD METHOD

<script type='text/javascript'>

<?php
    $i = 0;
    $group = [];
    $data = file("file.txt");
    foreach($data as $line)
    {
        $group[] = trim($line);
        if(count($group) == 3) // or ($i%3 == 0)
        {
             echo "var my_message = '$group[0]';
                    marker = new google.maps.Marker
                    ({
                        position: new google.maps.LatLng('$group[2]','$group[1]'),
                        map: map,
                    });";
             $group = []; // reset the group
        }
        $i++;
    }
?>

<\/script>

THE GOOD METHOD

Economic and optimized code Fetch all data in one time, outputed into a multi-dimensional array readable directly from javascript, and load markers and their messages in a while.

the outputed code will like that :

var coords = 
[
    ["Hello!","151.2069900","-33.8674870"],
    ["I am here!","-80.56344","43.471536666666665"],
    ["I was here before!","48.8566140","2.3522220"],
    ["I will come here one day!","22.851563","-79.278140"]
];

Now the code:

<script type='text/javascript'>
<?php
    $i = 0;
    $tmp = [];
    $geodata = [];
    $rawdata = file("file.txt");
    foreach($rawdata as $line)
    {
        $tmp[] = trim($line);
        if(count($tmp) == 3) // or ($i%3 == 0)
        {
            $geodata[] = $tmp; // add new geo group to the final cluster
            $tmp = []; // reset the group
        }
        $i++;
    }
    echo "var coords = ".json_encode($geodata).";";
?>


var infowindow = new google.maps.InfoWindow();
var marker, i;

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

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

<\/script>

ONLINE EXAMPLE

https://jsfiddle.net/mtroy/b14pjsro/6/embedded/result/

MTroy
  • 897
  • 9
  • 20
  • Hi! The code still doesn't work. It only shows the marker for current position. – ZigZagZebra Dec 20 '15 at 16:28
  • Yes it works, look this fiddle : https://jsfiddle.net/mtroy/b14pjsro/6/ I've fixed the filename "geo" to "file.txt", check validity of var coords; this is the only thing you should to getting work. (ah, try my php separatly and check his output must contain same format as var coords;) – MTroy Dec 21 '15 at 03:17