I'm trying to use template tags in my javascript to make it dynamic and load maps according to the address sent. My map is working and my geocode as well. I can even pass the latitude and longitude to the template, but when I place it inside of javascritp it doesn't work as expected.
For example:
if the {{longitude}} is -122,0843845 in the HTML, I get on my alert( {{longitude}} ) only -122. It seems that I there is a problem in Django converting a dot to comma, like -122.08... to -122,08. Either way it didn't work even when I tried with integers like -122.
Not sure if it is a float to string issue or something else, I'm quite new to javascript.
The code.
views.py
class ImovelDetail(DetailView): model = Imovel
def get_context_data(self, *args, **kwargs):
address = "1600 Amphitheatre Parkway, Mountain View, CA"
api_key = "AIzaSyAiw0iU0egdeVrOKboOOZ2n1WXS3Os0WgI"
api_response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}'.format(address, api_key))
api_response_dict = api_response.json()
if api_response_dict['status'] == 'OK':
context = super(ImovelDetail, self).get_context_data(**kwargs)
latitude = api_response_dict['results'][0]['geometry']['location']['lat']
longitude = api_response_dict['results'][0]['geometry']['location']['lng']
print(latitude)
context.update({'latitude': latitude, 'longitude': longitude})
return context
template.html
{% block js %}
<!-- <script>
SOMETHING THAT I TRIED
var latitude = {{ latitude }};
var longitude = {{ longitude }};
</script> -->
<script>
function initMap() {
var address = {lat: {{latitude}}, lng:{{longitude}} };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: address
});
var marker = new google.maps.Marker({
position: address,
map: map
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAiw0iU0egdeVrOKboOOZ2n1WXS3Os0WgI&callback=initMap"></script>
{% endblock %}