Using the google.maps.Geocoder::geocode in Javascript allows for powerful closure functionality to

Recently, I've been working with the google.maps javascript API v3. I'm faced with a challenge of translating a collection of civic addresses into markers on a google map while also adding 'click' listeners. What I aim for is that whenever a user clicks on a marker, a new window should open displaying a URL relevant to that specific address (ideally in another tab).

Despite my efforts, I have struggled to maintain the connection between the address and its corresponding URL due to my use of a javascript Closure in conjunction with the geocode() method provided by Google.

In my list, I have several addresses like:

var addresses = [ '123 street street', '124 street street' ];  
var urls = [ 'www.example.com/1', 'www.example.com/2' ];

Using the API, I proceed to geocode the addresses and place markers on the map as shown below:

for (var i = 0; i<addresses.length; i++)
{
    var address = addresses[i];
    var url = urls[i];
    geocoder.geocode(
        { 'address' : address },
    function(result, status) {
       var x = url // url == ""

       var marker = new google.maps.Marker({
          position: result[0].geometry.location,
          map: map,
          title:"Test"
       });

       google.maps.event.addListener(marker, 'click', function(event){
          alert(url);
          window.open(url);
       },false);
    }
}

While working within the anonymous function, I find myself wondering how to effectively utilize var url.

Answer №1

After some investigation, I discovered that the best solution was to divide everything into separate functions.

function displayLocation() {

    //geocoder = new Geocoder();

    for (var i = 0; i<addresses.length; i++)
    {
        var address = addresses[i];
        var url = urls[i];

        findLocation(address,url);
        wait(400);
      }
}

function findLocation(address,url)
{
    geocoder.geocode(
        { 'address' : address },
        function(result, status) {
            var marker;
            if(status == google.maps.GeocoderStatus.OK) {
                marker = new google.maps.Marker({
                    position: result[0].geometry.location,
                    map: map,
                    title:"Longueuil"
                });

            }
            linkUrl(marker, url);
        }
    );
}

function linkUrl(marker, url)
{
    google.maps.event.addListener(marker, 'click', function(event){
        alert(url);
        window.open(url);
    },false);
}

It appears that when a function is called, it creates permanent copies of the values stored in the variables and not just references to them.

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

When extracting the host URL and destination URL

When making an Ajax POST call to retrieve data from a file on a different server, I am encountering an issue where my host URL is being added to the destination URL for my AJAX request. Host URL: 192.168.1.2 Destination URL: 192.168.1.7/var/www/html/pfe/ ...

Tips for generating a random number and verifying if it matches the user input using inner HTML

I'm striving to create something more advanced than what I currently have, but I've hit a roadblock. My goal is to use the method Math.floor(Math.random()*11) to produce a random number. Then, I want to populate the inner HTML of a <p>, alo ...

Tips on saving HTML table information into a .txt document?

Welcome to my Unique HTML Table. <table> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Email Id</th> <th>Phone Number</th> <th>Prefered C ...

Send a PHP object to JavaScript using AJAX

I have a PHP script that successfully uploads a video to the Microsoft Azure service using an API. The API returns a StdObject file, which I then want to send back to JavaScript via AJAX. However, when I try to access the "asset" object in JavaScript, it a ...

Transform nested entities into a single entity where any properties that are objects inherit from their parent as prototypes

Exploring a new concept. Consider an object like: T = { a: 2, b: 9, c: { a: 3, d: 6, e: { f: 12 } } } The goal is to modify it so that every value that is an object becomes the same object, with the parent object as prototy ...

Issue: Unidentified supplier following JavaScript compression

Here is the AngularJS controller code that I am working with: (function() { 'use strict'; angular .module('app') .controller('TemplateCtrl', TemplateCtrl); function TemplateCtrl($http, $auth, $rootS ...

Troubleshooting a malfunctioning filter in Moongose for a Referenced Entity

I am dealing with two main Entities called Organization and Applications. A single organization has the capability to possess multiple Applications. const organization = mongoose.Schema( { name: { type: String, required: ...

Div automatically shifts to center position when other div elements vanish from view

I am new to jquery and currently working on a basic website. The site consists of three boxes, each of which, when clicked, causes the other two to fade out using the .fadeOut('slow'); method. However, there is an issue - all of the boxes are enc ...

Is it possible to invoke a JavaScript function from within a CSS file?

Currently, I am focusing on developing responsive web design and looking for ways to avoid creating multiple versions of each page based on screen width variations. The struggle lies in managing font sizes effectively. While attempting to style them using ...

Trouble altering material of object using keypress in three.js

I have been attempting to assign colors from an array to my object when a key is pressed, but I am only able to access the first element of the array. Is there another method that could be used for this purpose? One approach I considered was using a rando ...

bespoke theme background hue

I currently have material-ui@next installed and I am attempting to customize the background color of the theme. Here is what I have tried: const customizedTheme = createMuiTheme({ palette: createPalette({ type: 'light', primary: purple ...

How to dismiss a jQueryMobile dialog without triggering a page refresh

I've encountered a question similar to this before, but there wasn't any solution provided. The issue I'm facing is that I have a form and when a user clicks on a checkbox, I want to open a popup/dialog for them to enter some data. However, ...

Unusual CSS rendering hiccup

Using jQuery, I am manipulating the display of an <a> element. Depending on certain keypress events, it adds or removes a class from an <input> element (which controls the display) that is related as a sibling to the mentioned <a>. The i ...

Boost the animation smoothness for CreateJS's TweenJS to optimize its compatibility with three.js

Utilizing CreateJS's TweenJS in a 60fps three.js project is causing some jerkiness in the animation when moving objects. It seems like the objects are not being updated at the same frame rate. Check out this example here: https://jsfiddle.net/sccottt ...

What could be preventing the webpack dev server from launching my express server?

Currently working on a straightforward web application using express and react. The front-end React bundle is being served via the express server. Everything runs smoothly with my start script, which builds the front-end code and launches the express serv ...

How to retrieve a specific item from an array in JavaScript

I am retrieving this list from the server using PHP: ["Ak-Bulak","Balykchy","Batken"] How can I access it and insert it into select options using JavaScript? Here is what I have tried so far: for (var i in data) { $('#cities').append(' ...

Mongoose: No documents are being returned by the .find() method

UPDATE : Similar question posted here: Trouble with Mongoose find() method I'm still new to working with nodejs and nosql databases. Today, I am building an API that retrieves data from my user collection which currently has two entries : https://i. ...

Error: Unable to access the value property of a null object (React/JS/TS)

I created a function that dynamically determines the background color based on a specific value. const backgroundColorResolver = () => { allQuestions.map((aq) => { if (aq.averageAnswerValue <= 4) return "#EE7362"; if (a ...

Stream and upload videos, images, documents, and more all with the power of Laravel VueJs

I have successfully uploaded a video, but I am having trouble streaming it from the Laravel storage/app folder. Here is my Vue Js code: <video width="120" height="240" controls> <source :src="videoFullPath" type=& ...

Rendering objects in React is not allowed (encountered: [object Promise]). If you intended to display a group of children,

I am encountering an issue when trying to render this code, it keeps showing the message: "objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead." Can someone please assist ...