1

Here is my map code, it works perfect, no worries there. I'm just wondering how I get the Lat Lng values that the popup shows to insert into a form on-click?

So basically it would be like,

  1. User clicks map

  2. Coordinates popup (as they do now) and on same click coordinates fill form

  3. User hits submit!

Here is code,

<script>

var mymap = L.map('mapid').setView([38.47939, -99.49219], 5);

L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/outdoors-v9/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoiYnJldHQyMjI3OCIsImEiOiJjajAzNzZjZTkwOWNtMzJxbHZjMmVwZ2hyIn0.cWzkt6Gj_N3SZ8GKzqhByA', {
    }).addTo(mymap);

    var popup = L.popup();

    function onMapClick(e) {

        popup
            .setLatLng(e.latlng)
            .setContent("Copy and Paste into the Form \n" + e.latlng.toString())
            .openOn(mymap);

    }

    mymap.on('click', onMapClick);


</script>

I have also included my form in case it matters - the form works as is, you can manually type in data and it gets inserted into MySQL I just need help getting the automatic insert figured out... any help is much appreciated.

<div class="container">
  {% from "_formhelper.html" import render_field %}
  <form method=post action="/add_spot/">
    <dl>
      {{render_field(form.lat)}}
      {{render_field(form.lng)}}
    </dl>
    <p><input type=submit value=Submit></p>
  </form>
  {% if error %}
    <p class="error">{{error}}</p>
  {% endif %}
</div>
BrettJ
  • 1,176
  • 2
  • 17
  • 33

1 Answers1

2

In your onMapClicked function just use:

document.getElementById('your-input-id').value = e.latlng.toString();

Assuming you have the following HTML-Form:

<form>
    <input type="text" name="lat-lng" id="lat-lng" />
    <input type="submit" value="GO" />
</form>

This would be your function:

function onMapClick(e) {
    document.getElementById('lat-lng').value = e.latlng.toString();

    popup
        .setLatLng(e.latlng)
        .setContent("Copy and Paste into the Form \n" + e.latlng.toString())
        .openOn(mymap);
}
Sebastian
  • 1,642
  • 13
  • 26
  • I think you have it correct, however, the forms I'm trying to fill are generated by WTForms, and not just HTML forms. Is there a special way to achieve the same goal? – BrettJ Mar 10 '17 at 21:18
  • Thank you so much! I used your example combined with this [link](http://stackoverflow.com/questions/35707246/flask-wtf-quick-form-running-some-javascript-and-setting-a-form-variable) and it works!!!! – BrettJ Mar 10 '17 at 22:39