What is the process for having a Google Map marker direct to a specific URL?

Check out my HTML:

{% extends 'base.html' %}

{% block title %}Home{% endblock %}

{% block content %}
    <style>
        /* Customize the dimensions of the div element that houses the map */
        #map {
            height: 700px; /* Keep the height at 400 pixels */
            width: 100%; /* Adjust the width to fill the whole page */
        }
    </style>
    <!-- Define where the map will show up-->

    <div id="map"></div>
    <script>
        // Initialize and display 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>
    <!-- Get the API from the given URL
    * The async attribute lets the browser render the page while the API loads
    * The key parameter has your unique API key (not required here)
    * The callback parameter runs the initMap() function
    -->
    <script async defer
            src="https://maps.googleapis.com/maps/api/js?key=***&callback=initMap">
    </script>
{% endblock %}

I want this line to take me to:

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

redirects to /preview/{{ Listing.pk }} when you click on it.

How do I make the marker clickable? I've seen examples online but they look different from mine. Maybe it's because I have a mix of Google Maps code and Django template elements. Can I enclose my marker inside an tag with my URL in "href="?]

Answer №1

It's hard to believe that you didn't find any information, but I'm pretty sure it's all in the official documentation. Here's a simple way to do it:

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

To make things easier, just create a custom url property for the marker and set up a click event that directs to the specified URL when clicked.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I encountered an issue trying to animate an OBJ file in Three.JS, even after successfully loading it into the browser

I have encountered a challenge with scaling and animating an object loaded into my web browser using WebGL. The issue arises when attempting to include animation code within the render( ) loop function, specifically with the 'object' variable whi ...

Introducing a fresh addition to the array

I am looking for a way to create a new array without modifying the original one. Currently, there is a function that adds a new object to an existing array, but I need a different method to achieve this. Can someone suggest a solution? const arr = [ ...

Avoid mutating the prop directly and instead, utilize a data or computed property that is based on the value of the prop. The prop that is being mutated in this case is

Help me understand this issue that Vue is displaying, I am not sure what is going on. This is my progress element: <el-progress :percentage="percentCompleted" v-show="uploadingVideo"></el-progress> data() { return{ percentCompleted: 0 ...

Tips for achieving a gradual shadow effect on edges in THREE.js

I have come across some 3D scenes where I noticed a subtle gradient shadow near the edges of objects. This seems to enhance the definition between the two faces. How can we achieve this effect? Is it a result of shadow technology or light reflection techni ...

Return a string to the client from an express post route

I'm attempting to return a dynamically generated string back to the client from an Express post route. Within the backend, I've set up a post route: router.post('/', async (req, res) => { try { // Here, I perform computations on ...

What could be causing the error "Err: user.validPassword is not a function" to occur

I am in the process of developing a node.js app and I have implemented Passport js. After referring to the Passport-local documentation on their official website, I decided to utilize the local passport-strategy. However, I encountered an error stating tha ...

Is there a way to recycle an image and ensure that the web browser only needs to download it once?

Is there a way to effectively reuse the same image multiple times on my website without inefficiently downloading it each time? ...

Transferring Sound file between Django and Vue

I am attempting to transfer a audio file that was generated by gtts from Django to Vue using HttpResponse. In the views.py file of Django: f = open('path/of/mp3/file', 'rb') response = HttpResponse() response.write(f.read()) response[& ...

Incorporate information into a JSON structure within SAPUI5

While diving into SAPUI5, I decided to challenge myself by creating a basic form. Unfortunately, my attempts are falling short as the new entry I'm trying to add to my JSON model isn't showing up in the file when I run my code. No error messages ...

Upgrade scenes in ThreeJS by implementing cross fading between scenes from version 101 to 107

Discovering a helpful example by Fernando Serrano on how to smoothly transition between 2 scenes in ThreeJS was quite enlightening. I also stumbled upon this modified JSFiddle version using ThreeJS 101, which works well but faced an issue... Following the ...

Nextjs: If you encounter a file type that requires special handling, make sure you have the necessary loader configured to process it. Otherwise, the file will

I encountered the following error while attempting to run my Next.js application: ./node_modules/canvas/build/Release/canvas.node Module parse failed: Unexpected character '' (1:2) You may need an appropriate loader to handle this file type, curr ...

The issue persists where Chrome WebAPI's chrome.webRequest.onBeforeSendHeaders is failing to modify the parameters in the outbound requests

I have been attempting to include an IP address in the X-Forwarded-For parameter within the requestHeader, but my code does not seem to be working based on the examples provided in the Chrome API. Below is the code snippet I am currently using: var reque ...

Gaining entry to a JavaScript prototype method

I'm currently working on a prototype function called event. Prototype Func("input_element_id").event("keyup",function(){ alert("Works on keyup in an Input!"); } Func.prototype= { keyup: function(func){ //adding event listener and c ...

Access the original source code using jQuery

Is there a way to retrieve the raw HTML code (as seen in Chrome's source code window) using JQuery without having quotes converted to &quot or HTML symbols converted to text? I have tried using html() and text(), but neither method seemed to give ...

Problem with roles assigned through reactions on Discord

I've been working on a discord bot reaction roles command and everything seems to be going smoothly, except for one issue that I'm facing. After booting up the bot and running the command to create the embed, everything works fine. However, when ...

CKEditor not functioning properly when generated using AJAX and PHP in JavaScript file

I am facing an issue where I am using PHP and AJAX to generate a CKEditor textarea. The CKEditor JavaScript files are included in the main HTML file, and the PHP and AJAX functionalities are working correctly. However, when the form is displayed, the CKEdi ...

What is the best way to connect CSS properties to an image using JavaScript?

I recently used JavaScript to insert an image into a webpage, but I'm unsure of how to make changes to it or position it properly. Is there a way to connect CSS styles to the image, or is there another method to modify it without relying on CSS? < ...

Retrieving Categories using Django Model Queries Related to Posts

Looking for assistance with a Django model query. Currently developing a blog application, featuring models for posts and categories. On the categories page, I aim to display all categories along with one post from each category. For instance: view example ...

Inconsistent Animation Issue with jQuery Toggle for Expanding Div and Text

My expanding div functionality is almost perfect, but I've noticed that the transition when opening abruptly on divs with text. However, the closing transition is smooth. Can anyone help me make the opening transition as smooth as the closing one? Bel ...

Does anyone have any insights into why I am unable to render the data from the API?

Hello, I am relatively new to React and I am facing an issue with my API implementation. I am trying to create an API where users can add images, select a radio button, and send the data to the API to retrieve relevant image data. However, I am encounterin ...