Как сделать так, чтобы маркер Google Map перенаправлял на URL? - PullRequest
0 голосов
/ 23 октября 2019

Вот мой 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 ="?

1 Ответ

1 голос
/ 23 октября 2019

Не могу поверить, что вы ничего не нашли, я вполне уверен, что в официальной документации 1002 * есть что-то об этом. В любом случае это должно быть так просто:

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 свойство, которое вы определили выше).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...