如何将谷歌地图标记重定向到URL



这是我的html:

{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
<style>
/* Set the size of the div element that contains the map */
#map {
height: 700px; /* The height is 400 pixels */
width: 100%; /* The width is the width of the web page */
}
</style>
<!--The div element for the map --> flavor
<div id="map"></div>
<script>
// Initialize and add the map
function initMap() {
var map = new google.maps.Map(
document.getElementById('map'), {zoom: 4, center: {'lat': 42.6803769, 'lng': -89.03211}});
{% for Listing in posts %}
new google.maps.Marker({position: {'lat': {{ Listing.lat }}, 'lng': {{ Listing.lng }}}, map: map});
{% endfor %}
}
</script>
<!--Load the API from the specified URL
* The async attribute allows the browser to render the page while the API loads
* The key parameter will contain your own API key (which is not needed for this tutorial)
* The callback parameter executes the initMap() function
-->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=***&callback=initMap">
</script>
{% endblock %}

我需要排队:

new google.maps.Marker({position: {'lat': {{ Listing.lat }}, 'lng': {{ Listing.lng }}}, map: map});

单击时重定向到/preview/{{ Listing.pk }}

如何使我的标记成为可点击的链接?我在网上看了一些例子,代码似乎与我的大不相同。可能是因为我使用了GoogleMaps示例代码以及一些奇怪的Django模板。有没有办法把我的标记放在标签里,然后把我的URL放在"href="中?

我真的不敢相信你什么都没找到,我很肯定官方文档中有这方面的内容。无论如何,它应该像这样简单:

var myMarker = new google.maps.Marker({
position: {
'lat': {
{
Listing.lat
}
},
'lng': {
{
Listing.lng
}
}
},
map: map,
url: '/preview/{{ Listing.pk }}'
});
google.maps.event.addListener(myMarker, 'click', function() {
window.location.href = this.url;
});

在标记上定义自定义url属性,然后注册将当前URL更改为this.urlclick事件(您在上面定义的标记的url属性(。

最新更新