Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

python - How can i pass data from template in Django to Javascript in this specific case

I am using Google map api and i am trying to pass the data (longitude and latitude) to the template then use the data in the javascript to show a specific location.

location.html

{% for venue in property_listing %}
      {{ venue.address }}</br>
      <div id="long">{{ venue.longitude }}</br>
      <div id="lat">{{ venue.latitude }}</br>
{% endfor %}

javascript of the same page

<script>
      var latitude = REPLACE HERE;
      var longitude = REPLACE HERE;
      // Initialize and add the map
      function initMap() {
      // The location of Uluru
      var uluru = {lat: latitude, lng: longitude};
      // The map, centered at Uluru
      var map = new google.maps.Map(
          document.getElementById('map'), {zoom: 15, center: uluru});
      // The marker, positioned at Uluru
      var marker = new google.maps.Marker({position: uluru, map: map});
    }


    </script>

I am tried to replace the value literally but it wont work. What is the best way to solve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all you are assigning your data into a div. Which doesn't have a proper value attribute. Here is a work around by using getAttribute() method.

Assign an attribute named 'value' and it's corresponding data:

location.html

{% for venue in property_listing %}
      {{ venue.address }}</br>
      <div id="long" value="{{ venue.longitude }}">{{ venue.longitude }}</br>
      <div id="lat" value="{{ venue.latitude }}">{{ venue.latitude }}</br>
{% endfor %}

In your javascript function, access the data by getting the attribute of your div ids named value:

<script>
      var latitude = document.getElementById('lat').getAttribute("value");
      var longitude = document.getElementById('long').getAttribute("value");
      // Initialize and add the map
      function initMap() {
      // The location of Uluru
      var uluru = {lat: parseFloat(latitude), lng: parseFloat(longitude)};
      // The map, centered at Uluru
      var map = new google.maps.Map(
          document.getElementById('map'), {zoom: 15, center: uluru});
      // The marker, positioned at Uluru
      var marker = new google.maps.Marker({position: uluru, map: map});
    }
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...