Using Google Maps: Dragging the marker constantly results in the same position being returned by GetPosition

I'm having an issue with a for loop that creates more than 100 markers. Every time I drag a random marker, the console logs the same position even though the "Point" value is different when dragging another marker. Why am I consistently getting the same position? Interestingly, when I test it with only 1 marker, the code works as expected.

Here's a snippet of the code:

coordinates.forEach(function(entry) {   

    if(!isOdd(number)){
        marker_lat = entry;
        number++;
    } else {
        marker_lng = entry;             
        var myLatlng = new google.maps.LatLng(parseFloat(marker_lat),parseFloat(marker_lng));

        marker_icon = "red.png";

          mark = new google.maps.Marker({
           position: myLatlng,
           map: map,
           title: number,
           icon: marker_icon,  
           draggable:true
         });                
        number++;

        google.maps.event.addListener(mark, 'dragend', function() { 
                id_point = $(this).attr("title");
                console.log("Point: "+id_point);
                console.log(mark.getPosition().lat());// Always the same position
                console.log(mark.getPosition().lng());// Always the same position
        });
    }
}); 

Answer №1

The listener passes the marker as a parameter to the function. Give this code a try:

google.maps.event.addListener(mark, 'dragend', function(m) { 
    id_point = $(this).attr("title");
    console.log("Point: "+id_point);
    console.log(m.latLng.lat());
    console.log(m.latLng.lng()); /* This is different from your existing code. I haven't tested it yet, but it worked on my previous project. */
});

Additionally, you can use getPosition() with this:

google.maps.event.addListener(mark, 'dragend', function(m) { 
    id_point = this.title;
    console.log("Point: "+id_point);
    console.log(this.getPosition().lat()); // Same as above
    console.log(m.latLng.lat());
});

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

Is it possible to specify the input language for a textbox or textarea in a web form?

I am currently working on developing a website in Urdu language, with features similar to that of a blogging platform. To ensure that all posts are written only in Urdu, I am exploring different options. One idea I have is to use a Javascript code that ca ...

What about nested elements with percentages, set positions, and fixed placements?

Picture: https://i.sstatic.net/KFNR1.png I am working on a design with a yellow container div that I want to keep at 50% width of the window. Inside this container is a purple image div that stretches to 100% of the parent container's width, and ther ...

Navigating through the properties of a JSON object and traversing the React state leads to encountering the error message 'state undefined'

Apologies if I seem a bit lost, but I'm attempting to assign a JSON object to a component's state for rendering purposes. This is the current setup within my component: render: function() { this.serverRequest = $.get(this.props.source, func ...

Is there a Facebook application embedded in the user's wall?

Is it feasible to create a website similar to YouTube, where users can share it on Facebook and run the app (in this case, the video player) directly on their wall without having to visit the YouTube page? If it is possible, is this functionality limited ...

send the value of a variable from a child component to its parent

I have created a typeahead component within a form component and I am trying to pass the value of the v-model from the child component to its parent. Specifically, I want to take the query model from the typeahead component and place it in the company mode ...

Problem with autocomplete functionality in Angular Material's md-contact-chips

Having some trouble with the autocompletion feature of md-contact-chips. I want to capture the $query as soon as someone starts typing. HTML <md-contact-chips ng-model="members" md-contacts="querySearch($query)" md-contact-name="fullname" ...

React.js: Endless rendering occurs when using setState as a callback function, even after props have been destructured

Issue I am facing a problem with my child component that receives button id-name configurations as props. It renders selectable HTML buttons based on these configurations and then returns the selected button's value (id) to the callback function with ...

HTML experiences confusion as JSON tosses undefined data

Can someone assist me with API integration? I am new to this and trying to display the Poster, Title, and Year from an API URL. Here is the code I have been working on. When I log in, it shows JSON in an array but throws "undefined" in front-end. Your help ...

Design of Redux middleware with focus on return values

I just finished learning about redux middleware, and it seems really useful. However, I have a question regarding the return values of middleware. I understand that some middleware return values (such as redux-promise), while others like logging do not - ...

Create a custom key in SJCL that has an expiration time set for automatic deletion

My current project involves encrypting and decrypting data on the client-side using the SJCL library. However, I have a specific requirement that the encryption key must expire after a certain scheduled time. So my question is this: Can a key with an e ...

Is there a way to confirm the presence of multiple attributes in a JSON format using JavaScript?

Currently, I am developing a module that processes multiple complex JSON files and requires a method to notify users if certain elements are missing. Although the current approach works, I can't shake the feeling that there must be a more efficient a ...

What is the best way to utilize mouseenter and mouseleave events concurrently?

I need some assistance with my website's star rating feature. When a user hovers over the stars, a popover should appear, and when they move their mouse away, the popover should disappear. Currently, I am using jQuery to achieve this functionality: $( ...

In what way does the Node console showcase decimal numbers in floating point format?

While I understand the challenges of representing base 2 numbers in base 10 due to rounding issues in programming languages, my experience with the NodeJs console has left me puzzled. It is a known fact that base 2 numbers cannot perfectly represent 0.1 in ...

Issue with form array patching causing value not to be set on material multiple select

When attempting to populate a mat-select with multiple options using an array of ids from Firestore, I encountered an issue. The approach involved looping through the array, creating a new form control for each id, and then adding it to the formArray using ...

Guide to configuring a service worker to manage the main website path

My website is hosted at https://xxxxxx.com. I have set the scope of the service worker file sw.js to /, but it seems that the service worker is unable to control the page https://xxxxxx.com. However, it can control other pages like https://xxxxxx.com/, e ...

Is there a way to ensure that when a user updates the src attribute of a video element in a REACT Gutenberg block, the change is immediately visible to them?

I am currently in the process of developing a custom Gutenberg block for WordPress by utilizing @wordpress/create-block. As part of this project, I am incorporating the MediaUpload React component, which can be found at this link. Within the block, there ...

jQuery does not support iterating over JavaScript objects

Here is the code snippet I am working with: $(obj).each(function(i, prop) { tr.append('<td>'+ i +'</td>' + '<td>'+ prop +'</td>'); }); Intriguingly, the data in $(obj) appears as: Obje ...

The Server Side Rendering in (Vue+Express) faltered due to inconsistencies in hydration

While browsing Vue's official website, I came across a concise example demonstrating how to implement server-side rendering (SSR) using Vue. (https://stackblitz.com/edit/vue-ssr-example-qaztqn?file=package.json) Intrigued by this example, I decided ...

disregarding specific characters in a JavaScript string

Currently, I'm utilizing the themoviedb API to incorporate movie posters onto a webpage using the JSON data they provide. The snippet of code I have is as follows: <div id="poster"></div> Here is the JS/jQuery code snippet: $(document) ...

Ways to iterate and combine two associative arrays in jQuery

I have a total of 15 sections, each known as bases, with their own alphabet buttons. My goal is to link the alphabet letters with their corresponding base/section. For instance, if a user clicks on the letter "B" under base 7, I want to show that the user ...