I'm encountering an undefined JavaScript variable, how should I proceed?

$(function(){

    //Location was "set". Perform actions.
    $("#geocodesubmit").click(function(){
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            $("#map_canvas").show();
            var myOptions = {
                zoom: 15,
                center: results[0].geometry.location,
                mapTypeControl:false,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                scrollwheel:false,
            };
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);  
            var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    draggable:true
            });
         } 
       });

        return false;
    });

    //Marker was dragged. 
    google.maps.event.addListener(marker,"dragend",function(){
            alert('hi');
    });
});

I have implemented code that generates a Google map and a new marker when the user clicks on a button. However, I encountered an issue where the marker is not getting binded properly.

Upon loading the page, an error occurs:

Uncaught ReferenceError: marker is undefined
.

This problem arises because the marker is only initialized after the button click event. How can I successfully bind the marker in this scenario? (I prefer to delay the map loading until the button is clicked to avoid display issues)

Answer №1

Place the addListener function inside the click event handler.

Answer №2

Check out this solution

$(function () {
    var marker;
    //Execute actions when location is set
    $("#geocodesubmit").click(function () {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
            'address': address
        }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                $("#map_canvas").show();
                var myOptions = {
                    zoom: 15,
                    center: results[0].geometry.location,
                    mapTypeControl: false,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    scrollwheel: false,
                };
                var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
                marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    draggable: true
                });
            }
        });

        return false;
    });
    //Listen for marker drag event
    google.maps.event.addListener(marker, "dragend", function () {
        alert('hi');
    });
});

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

The error message indicates that the property 'current' is not found in the type '[boolean, Dispatch<SetStateAction<boolean>>]'

During my React/Typescript project, I encountered an issue involving cursor animations. While researching the topic, I stumbled upon a CodePen (Animated Cursor React Component) that functioned perfectly. However, when attempting to convert it into a Types ...

Tips for including multiple spaces within a cell of a table

I've come across an issue while working on a table and attempting to insert text with multiple spaces. For example, I want to add the text HELLO<1stSPACE><2ndSPACE>WORLD. However, when I enter it as HELLO WORLD, it only displays with a si ...

Does Eslint's no-restricted-imports rule only limit imports from the package's root directory?

For example, I'm looking to limit the usage of importing react-use, while still permitting react-use/lib/usePrevious. I attempted this: rules: { 'no-restricted-imports': [2, { patterns: [ 'react-use', ] }], }, As ...

The state object in Redux Toolkit remains static, resulting in the error message "Uncaught TypeError: Cannot assign to read only property 'property-name' of object '#<Object>'"

I'm facing an issue where I am trying to update the data of a state object in Redux Toolkit but it's not changing, and instead throwing an error that says Uncaught TypeError: Cannot assign to read only property 'status' of object ' ...

The presence of Bootstrap remains hidden unless space is designated for it

Question about Bootstrap 5.1.3: Is there a way to hide elements on a page using the bootstrap class ".invisible" without allocating space for them? Currently, when the elements are set to visible using the class ".visible", they occupy space on the page ...

Is there a way to adjust the brightness of specific sections within an image using html, css, and js?

I am working on a project where I have an image with tags underneath that correspond to different parts of the image. For example, if the image is of a dog, one of the tags could be 'nose', indicating the portion of the image around the dog' ...

Postman grants me the cookie, yet Chrome doesn't seem to deliver it

As I attempt to set a cookie named auth, containing the user's ID signed with JWT, I am puzzled by not seeing the auth cookie in Chrome when visiting http://localhost:5000/. Instead, I only observe these two cookies; https://i.sstatic.net/p0Foo.p ...

I'm having trouble grasping the sequence of events in this async example

Currently, I'm delving into the world of JavaScript and Node.js, but I find myself facing challenges with asynchronous execution. I have a piece of code that may not be following best practices, but I am eager to understand why the file remains open w ...

Activate the HTML drop-down option upon selecting the radio button, or the other way around

I'm attempting to accomplish a task. Below is the code snippet I am working with: <form> <input type='radio' name='radio_flavour' checked/>Unique flavour<br/><input class='double-flavoured' type=&apo ...

Utilizing the data sent to a modal to enhance the functionality of the code by combining it with the src attribute of an <embed> element

I am trying to pass a dynamic string of data to a Bootstrap modal using the data-val attribute in an HTML table. <td <button type="button" class="btn btn-success btn-xs" data-val="<?php echo $row['order_id']; ?&g ...

What is the best way to display the legend on my PieChart?

I am attempting to display the names of colors in my PieChart as a legend. Here is the JSON data: { "choice": "20-29 yrs. old", "count": 4 }, { "choice": "30-39 yrs. old", "count": 2 }, { "ch ...

A guide on utilizing ClassName to insert new items into a DIV

Original HTML code: <span class="specLink"> <specialty><a title="Plastic Surgery" href="link2.aspx">Plastic Surgery</a></specialty> </span> <br /> <span class="specLink"> <specialty2><a titl ...

Adaptable Collection of 4 Images

I am facing a challenge in replicating eBay's 'Today' featured seller layout with 4 square images creating one box (refer to the image). I am using Bootstrap for this task, and I am finding it difficult to comprehend how to achieve this. I h ...

Guide to utilizing a JWT token within an httpOnly cookie for accessing a secured API endpoint

Utilizing next.js and next-auth for user login authentication with an API. Once the login is successful, a httpOnly cookie named __Secure-next-auth.session-token is stored in the browser. The following is a sample value (not actual data): eyJhbGciOiJIUzUxM ...

The Challenge of Refreshing Static Site Generation in NextJS Version 13

I've encountered a problem with updating data on a basic data page. The situation is simple: there's a page that shows category data and another page that allows editing of the same data. After making edits and returning to the list page, I expec ...

Navigating from Page 1 to Page 2 and then returning to Page 1 using the browser's back button causes Page 1 to malfunction in NextJS version 13

I am currently using next version 13.4.5 and implementing routing with typescript through /app. On my first page, I have a <Link> (next/link) element that takes me to Page 2. However, when I use the browser back button to return to page 1, the layou ...

Dynamic SVG circles with timer and progress animation

Is there a way to modify the following: var el = document.getElementById('graph'); // get canvas var options = { percent: el.getAttribute('data-percent') || 25, size: el.getAttribute('data-size') || 220, lineW ...

What is the best way to manage error handling in various locations within an Angular stream?

Currently, I am working on ensuring that errors are handled properly in a stream where the id of a group is retrieved first and then used to obtain profile information. I want to easily identify whether the error is occurring during the retrieval of the g ...

What is the best way to position a static element next to a Vue draggable list?

I'm currently working on implementing a feature to display a list of draggable elements using vue-draggable. These elements are occasionally separated by a fixed element at specified position(s). My approach so far has involved creating a separate el ...

The IMG directory cannot be stored in the database but can be viewed using the same variables used in the query

I'm facing an issue while trying to upload an image to my server using a form created by Sanwebe. You can find the form here. After pressing the upload button, the new thumbnail loads perfectly fine. However, for some reason, the image is not being up ...