Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

newline in Leaflet marker popup text

I have a form to associate some text to a marker on a Leaflet map:

<form action="map.php" method="POST">
 <section>
  <label>write some text here</label>
   <textarea id="text" rows="3" name="area"></textarea>
 </section>

 <input type="submit" value="show map" />
</form>

As you can see above, the content of the textarea is passed to the page map.php, where a map is shown. On the map, the place marker is shown, and a popup contains the text posted through the textarea (variable $text):

<?php
$text = htmlspecialchars($_POST["text"]);
?>

<center>
 <div id="map" class="embed-container"></div>
</center>

<script>
  var map = L.map('map').setView([46.13, 11.11], 9);
  L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    {
      attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
      maxZoom: 17,
      minZoom: 9
    }).addTo(map);
</script>
<script>
  var icon = L.icon({
        iconUrl: 'img/gps.png',
        iconSize: [25, 25],
        });
  var marker = L.marker(['<?=$latitude;?>', '<?=$longitude;?>'], {icon: icon}).addTo(map);
  marker.bindPopup('<?=$text;?>');
</script>

The problem is that if I press ENTER while I write something in the textarea, nothing is passed to the popup marker. I tried with \n and such, but nothing works. They are shown in the popup text as strings, not as newlines.

Any ideas?

like image 905
Alex Avatar asked Dec 23 '22 23:12

Alex


1 Answers

The problem is that if I press ENTER while I write something in the textarea, nothing is passed to the popup marker.

This is inaccurate. The HTML inside the popup is receiving a newline character.

The problem is that the newline character is being displayed as collapsed whitespace. This is the default in HTML. Let me quote the documentation for the white-space CSS property, inherited by default by all HTML elements:

normal

  • Sequences of whitespace are collapsed. Newline characters in the source are handled as other whitespace. Breaks lines as necessary to fill line boxes.

HTML collapses whitespace characters, including tabs and line breaks (but excluding &nbsp;s).

HTML and whitespace

Text inside Leaflet popups simply follow the same rule. Replace your newlines with HTML <br> line breaks, or otherwise wrap every line in a block-level element like a <div>.

Popups and newlines

If you are using php, the easiest way is to use the nl2br function. This is not necessarily the best way, as it is very prone to allowing XSS attacks in the hands of inexperienced developers. Using htmlspecialchars will not help if you are outputting JavaScript strings, enclosed in quotes. For these cases I recommend using json_encode to provide the quotes and the quote scaping, i.e. var foo = <?= json_encode(nl2br(str)); ?>;

like image 120
IvanSanchez Avatar answered Dec 26 '22 15:12

IvanSanchez