我正在尝试在 JavaScript 中使用模板标签使其动态并根据发送的地址加载 map 。我的 map 和地理编码都可以正常工作。我什至可以将纬度和经度传递给模板,但是当我将其放置在 javascritp 中时,它无法按预期工作。
例如:
如果 HTML 中的 {{longitude}} 为 -122,0843845,则我的警报( {{longitude}} )仅为 -122。看来我在 Django 将点转换为逗号时出现问题,例如 -122.08... 到 -122,08。不管怎样,即使我尝试使用 -122 这样的整数,它也不起作用。
不确定这是 float 到字符串的问题还是其他问题,我对 JavaScript 很陌生。
代码。
View .py
类 ImovelDetail(DetailView): 型号=伊莫维尔
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
模板.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 %}
最佳答案
这是因为 javascript 在十进制数字中使用点。因此,如果您将数字传递给 JavaScript,则需要使用点。像这样:159.0857 如果你用逗号传递它,javascript会将其四舍五入
如果您使用带逗号的坐标(这不是很好的方法)。然后你需要替换逗号。也许与 custom filter 。但我怎么说呢。使用带点的十进制数会更好。
当然,如果页面上有一些对象,您可以为 html 元素分配坐标(带点)。
<p class="address" latitude="49.055" longitude="40.808">Your address</p>
然后您可以通过 JQuery 或 javascript 获取该值。
如果您的经纬度中有逗号,则必须先替换它。在你看来,试试这个:
return context.update({'latitude': float(latitude.replace(',','.')), 'longitude': float(longitude.replace(',','.'))}
已编辑
最后可能导致此问题的一件事(您说在标准输出上没问题)是本地化。检查这个answer
您必须设置USE_L10N=False
关于javascript - Django:在 Google map 的 javascript 中使用模板标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43079756/