An array containing various sets of Google map coordinates

I need to save the latitude and longitude coordinates of points within an object, and then store all these objects in an array. However, I am encountering an issue where each object is being added to the array multiple times.

Here is the code snippet I am using:

function initMap1() {
  var mapDiv = document.getElementById('frame1');
  map = new google.maps.Map(mapDiv,{
    center: {lat: 3.875083, lng: 11.516110},
    zoom: 14,
    disableDoubleClickZoom: true
  }); 
  var Data = [];
  google.maps.event.addListener(map,'dblclick',function(e){
    var Object = {};
    lat.val(e.latLng.lat());
    lng.val(e.latLng.lng());
    $('#btn_modal').click(function(){
      Object['lat'] = e.latLng.lat();
      Object['lng'] = e.latLng.lng();
      Object['icone'] = nat.val();
      var marker = new google.maps.Marker({
        position: {lat:e.latLng.lat(),lng:e.latLng.lng()},
        map: map,
        icon:'img/icones/'+(nat.val())+'.png',
        title: nat.val()
      });
    });
    Data.push(Object);
  });
}

Answer №1

To ensure that your object is only pushed to the data array when you click your modal button, it is important to move the push call inside the event being created. Otherwise, the object will be pushed to the array every time the map is double-clicked.

Here is the revised code:

$('#btn_modal').click(function(){
            Object['lat'] = e.latLng.lat();
            Object['lng'] = e.latLng.lng();
            Object['icone'] = nat.val();
            var marker = new google.maps.Marker({
                position: {lat:e.latLng.lat(),lng:e.latLng.lng()},
                map: map,
                icon:'img/icones/'+(nat.val())+'.png',
                title: nat.val()
            });
     ----> Data.push(Object);
        });

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

Execute AngularJS $resource request to alternative URL if no response received within specified time frame

In the event that my primary API is unresponsive, I want my front-end application to automatically switch to a secondary API. For instance, when calling results in a net::ERR_CONNECTION_TIMED_OUT error (as seen in Chrome XHR response), signifying that th ...

Encountering a 'next' error with Facebook Connect

I'm currently in the process of testing out the new Facebook authentication system, but I'm facing some issues with getting the login to function properly. Here's the error message I'm encountering: API Error Code: 100 API Error Desc ...

"Why does the useEffect in Next.js fire each time I navigate to a new route

Currently, I have implemented a useEffect function within the Layout component. This function is responsible for fetching my userData and storing it in the redux-store. However, I have noticed that this function gets triggered every time there is a route c ...

Varied elevations dependent on specific screen dimensions

There seems to be a minor issue with the height of the portfolio container divs at specific window widths. The problematic widths range from 1025 to 1041 and from 768 to 784. To visualize this, try resizing your browser window to these dimensions on the fo ...

Send a batch of files using XMLHttpRequest to a Express.js 3.5 Server

I am currently working on creating a file uploader using the native FileAPI in JavaScript. I am looking to upload the files via XMLHttpRequest to a Node.js server that utilizes Express.js. The file reading aspect is functioning properly, and when I upload ...

The audio directory is not included in the build of the Ionic framework, causing it to be skipped and absent

Recently, I've been working on an Ionic/Cordova app and came across a folder labeled /audio which consists of mp3 files: /www /assets /audio file.mp3 /css /js config.xml index.html The issue at hand is that the /audio directory is n ...

When utilizing jQuery in DOM, a JSON array may display a combination of undefined values and actual data

Although I am new to JS and jquery, I attempted to load some basic JSON data into my HTML page. In previous projects, I managed this without any issues, but in this case, multiple data fields are displaying as undefined. JSON DATA: {"employment": [ ...

Encountering an issue with Angular 5.2 application build on VSTS build server: Running into "CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory" error

Out of nowhere, the builds began failing with the following error : 2019-01-03T12:57:22.2223175Z EXEC : FATAL error : CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory error MSB3073: The command "node node_modules/webpack/bin/w ...

Transform the JSON string into a JSON object to avoid modifying the base jquery.dataTables.js script

When using ASP.net MVC on the server side, I have a model class that I usually serialize with JsonConvert.SerializeObject(DataTableModel) and send back to datatables.js. The resulting JSON data looks like this:_fnBuildAjax.baseAjax >> success as show ...

Utilize AngularJS to interact with RESTful web services

Here is the JSON data fetched from my web service: [{"cameraid":"ggh","timestamp":"2016/05/10 01:31","filename":"ffffpg"}, {"cameraid":"mason","timestamp":"2016/05/10 05:31","filename":"aaa.png"} This is the HTML code I have: <!doctype html> <h ...

Error encountered during JSON parsing: unexpected non-whitespace character found after the JSON data on line 1

I have implemented a simple JavaScript code (using AngularJS, but that's not important) like this: app = angular.module('app', []); app.controller("NavCtrl",function($scope,$http){ var serviceBase = 'api/'; $http.get(serv ...

Issue encountered while attempting to pass a function to a child component in React (Uncaught error: TypeError - result is not a function)

How can I pass the result obtained from an API call made in a child component to the parent component? Let's take a look: PARENT COMPONENT: const Parent = () => { function logResult(resultFromAPI) { console.log(resultFromAPI); } ...

instructions on invoking a function within the knockout $.getJSON() operation

I am currently experimenting with a basic knockout script (still in the learning process). $.getJSON(clientUrl + "/list/" + 1, function (data) { var viewModel = { clients: ko.observableArray(data) }; ko.applyBindings(viewModel); }); The initial arg ...

Printing the selected value from a drop-down box in HTML with JavaScript

I'm in the process of creating a web page structured like this: <html> <head> <title>Bug UI</title> </head> <body> <script> function myfunc() { //what should I include here?? } </script> <form> ...

Struggling with deploying Next.js on Vercel

Encountered an issue while trying to deploy a project on Vercel. The error message is as follows: fileName: comps/Navbar.js imported as import Navbar from "./Navbar"; 16:36:51 ModuleNotFoundError: Module not found: Error: Can't reso ...

Deactivate an element completely, preventing any interaction with it, including disabling links that trigger other JavaScript functions

<li class=" active"> <input class="check-shopby" type="checkbox" onclick="$(this).next().click()" checked="checked"> <a class="checked" href="http://mysite/~dev433/products//cooking/cook-tops.html" onclick="$(this).previous().checked = f ...

Utilizing adapter headers in contexts other than ActiveModelAdapter

I have successfully implemented my authorization system with Ember Data. All my ember-data calls are secure and signed correctly using adapter.ajax() instead of $.ajax. However, I am facing a situation where I need to utilize a third-party upload library t ...

Problems with Angular UI Router: Functions not functioning properly within the template

Currently, I am delving into the realm of Angular UI Router in order to effectively manage different sections of my application. If you'd like, check out this plunkr (http://plnkr.co/edit/KH7lgNOG7iCAEDS2D3C1?p=preview) Here are some issues that I&a ...

Issue with AngularJS: 'FileConstructor is not a valid constructor'

Error Alert: The FileConstructor is not functioning as expected, displaying the error message 'FileConstructor is not a constructor (evaluating 'new File([blob], "filename.png")') Upon researching, I came across a related query Alternative ...

Is it necessary to execute Commit and Begintransaction in SELECT queries?

I'm an MySQL beginner. Should we use commit or beginTransaction in SELECT statements? Let's say the query looks like this db.query("SELECT * FROM my_table") In this scenario, do we need to use commit or beginTransaction? db.query(&quo ...