1

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 %}
0

1 Answer 1

2

It is because javascript uses dot in decimal numbers. So if you pass number to javascript you need use dot. Like this: 159.0857 If you pass it with comma javascript will round it

If you are using coordinates with commas (which is not very good approach). Then you need to replace comma. Maybe with custom filter. But how I said. It will be much better use decimal numbers with dots.

Of course if you have some objects on the page you can assign coordinates (with dots) to the html elements.

<p class="address" latitude="49.055" longitude="40.808">Your address</p>

and then you can get this values via JQuery or javascript.

If you have comma in your lat and lon, you have to replace it first. In your view try this:

return context.update({'latitude': float(latitude.replace(',','.')), 'longitude': float(longitude.replace(',','.'))}

Edited
The last thing which could make this problem (you said it is OK on your standard output) is localization. Check this answer

You will have to set USE_L10N=False

Sign up to request clarification or add additional context in comments.

4 Comments

I tried it like this context.update({'latitude': float(latitude), 'longitude': float(longitude)}) it prints to Terminal as dotted floats either way and in the template it appears as a comma. I also tried with regular integers like 122 but nothing worked.
Last try what makes sense to me is a localization . Try attached link.
I got it! Your answer helped a lot! Passing it as a string worked. I added latitude = str(latitude) and longitude = str(longitude) to my view and it went alright to javascript.
I don't help you very much but glad to hear it :-) it will be maybe the localization problem. This will be workaround, sending as string. You should try set localization.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.