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?
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>
This should do the trick:
<script>
var latitude = {{ venue.latitude }};
var longitude = {{ venue.longitude }};
// 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.