如何使Google Map标记重定向到URL? [英] How can I make a Google Map marker redirect to a URL?

查看:98
本文介绍了如何使Google Map标记重定向到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}}

如何使标记成为可点击的链接?我在网上查看了一些示例,该代码似乎与我的代码有很大不同。可能是因为我正在使用Google Maps示例代码以及一些奇怪的Django模板化功能。有没有办法我可以将标记放在标签内,然后将URL放入 href =?

How can I make my marker a clickable link? I've looked at some examples online and the code seems vastly different from mine. Probably because I'm using the Google Maps example code along with some weird Django templating things. Is there a way I can just but my marker inside an tag and put my URL in "href="?

推荐答案

我真的不相信您没有找到任何东西,我很肯定在官方文档。无论如何,它应该像这样简单:

I can't really believe that you didn't find anything, I'm quite positive there's something about that in the official documentation. Anyway, it should be as easy as this:

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 标记上的>属性,然后注册 click 事件,该事件会将当前URL更改为 this.url (标记的 url 您在上面定义的属性)。

You define a custom url property on the marker, then register a click event that changes the current URL to this.url (the marker's url property you defined above).

这篇关于如何使Google Map标记重定向到URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆