Django:在Google地图的javascript中使用模板标记
我试图在javascript中使用模板标记使其动态化,并根据发送的地址加载映射。我的地图在工作,我的地理代码也在工作。我甚至可以将纬度和经度传递给模板,但当我将其放在JavaScriptp中时,它并没有按预期工作 例如: 如果HTML中的{longitude}是-1220843845,我只会得到-122的警报({longitude})。我觉得Django把点转换成逗号有问题,比如-122.08。。。至-122,08。不管怎样,即使我尝试使用像-122这样的整数,它也不起作用 我不确定这是一个浮点到字符串的问题还是其他什么问题,我对javascript非常陌生 密码 views.py 类ImovelDetail(详细视图): 模型=ImovelDjango:在Google地图的javascript中使用模板标记,javascript,django,google-maps,django-templates,Javascript,Django,Google Maps,Django Templates,我试图在javascript中使用模板标记使其动态化,并根据发送的地址加载映射。我的地图在工作,我的地理代码也在工作。我甚至可以将纬度和经度传递给模板,但当我将其放在JavaScriptp中时,它并没有按预期工作 例如: 如果HTML中的{longitude}是-1220843845,我只会得到-122的警报({longitude})。我觉得Django把点转换成逗号有问题,比如-122.08。。。至-122,08。不管怎样,即使我尝试使用像-122这样的整数,它也不起作用 我不确定这是一个浮点
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 %}
{%block js%}
函数initMap(){
var地址={lat:{{latitude}},lng:{{longitude}};
var map=new google.maps.map(document.getElementById('map'){
缩放:15,
中心:地址
});
var marker=new google.maps.marker({
职位:地址:,
地图:地图
});
}
{%endblock%}
这是因为javascript在十进制数字中使用点。所以,若您将数字传递给javascript,则需要使用点。像这样:159.0857
如果用逗号传递,javascript会将其四舍五入
如果使用带有逗号的坐标(这不是很好的方法)。然后你需要替换逗号。也许和我一起。但我是怎么说的。最好使用带点的十进制数字
当然,如果页面上有一些对象,可以为html元素指定坐标(带点)
<p class="address" latitude="49.055" longitude="40.808">Your address</p>
已编辑造成这个问题的最后一个原因是本地化(您说在标准输出上可以)。检查这个
您必须设置
USE\u L10N=False
我像这样尝试context.update({'latitude':float(latitude),'longitude':float(longitude)})
它以虚线浮点数的形式打印到终端,在模板中以逗号的形式显示。我也尝试过像122这样的正则整数,但没有任何效果。试试附加的链接。我知道了!你的回答帮助很大!把它当作一根绳子传递是有效的。我在我的视图中添加了latitude=str(latitude)
和longitude=str(longitude)
,这对javascript来说没什么帮助,但很高兴听到:-)这可能是本地化问题。这将是一种变通方法,以字符串形式发送。您应该尝试设置本地化。
return context.update({'latitude': float(latitude.replace(',','.')), 'longitude': float(longitude.replace(',','.'))}