How can I make a Google Map marker redirect to a URL?

孤街醉人 提交于 2019-12-25 18:48:10

问题


Here is my 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 %}

I need to make the line:

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

redirect to /preview/{{ Listing.pk }} when clicked.

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="?


回答1:


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;
});

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).



来源:https://stackoverflow.com/questions/58527279/how-can-i-make-a-google-map-marker-redirect-to-a-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!