Problem with geocoding to retrieve a list of terrestrial coordinates

I am currently working on developing a functionality that can return an array of land-based coordinates. I have utilized Google's geocoder to create individual land-based coordinates successfully, but now I want to implement it in a way where an array of these coordinates is generated by continuously calling the function using a while loop until the desired number of coordinates is achieved. However, when attempting to execute this function in JSFiddle, the page crashes.

I cannot pinpoint the reason behind this issue as I had anticipated the reduction of coordinates each time a location-based coordinate is found. If no coordinate is found, the function should continue to be called until one is eventually located (which is expected to happen at some point in the future).

Any help or guidance on this matter would be greatly appreciated. You can access the public fiddle through this link: http://jsfiddle.net/grabbeh/sajfb/


var map;
var coords = [];
var geocoder = new google.maps.Geocoder();

window.onload = function () {
  center = new google.maps.LatLng(40.717, -74.006);

    var options = {
    zoom: 1,
    center: center,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };

  map = new google.maps.Map(document.getElementById('map'), options);
};

function addMarkersToMap(places) {
  for (var i = 0, j = places.length; i < j; i++) {
     placeMarker(places[i]);
  };
};

function placeMarker(location) {
 var marker = new google.maps.Marker({
    position: location,
    map: map,
    flat: true,
   });
};

function randomLandBasedCoords(number, fn) {
  if (number > 0) {
    while (number > 0) {
        // create random coordinate
        var lng = (Math.random() * 360 - 180);
        var lat = (Math.random() * 180 - 90);
        var randomCoordinate = new google.maps.LatLng(lat, lng);

        // call geocoder function to check if coordinate is land-based with a timeout to control flow
        setTimeout(geocoder.geocode({
            location: randomCoordinate
            }, function (results, status) {
               if (status == "OK" && results) {
                  var landCoordinate = randomCoordinate;
                  coords.push(landCoordinate);
                  number--;
               }
           }), 250);
       }
   }
   return fn(coords);
}

Answer №1

Here is a function that generates random land-based coordinates:

function generateRandomLandCoordinates(number, callback) {
    // Generate random latitude and longitude
    var longitude = (Math.random() * 360 - 180);
    var latitude = (Math.random() * 180 - 90);
    var randomCoordinate = new google.maps.LatLng(latitude, longitude);

    // Check if the coordinate is land-based using geocoder function
    geocoder.geocode({
        location: randomCoordinate
    }, function (results, status) {
        if (status == "ZERO_RESULTS") {
            generateRandomLandCoordinates(number,callback);
        } else if (status == "OK" && results) {
            var landCoordinate = randomCoordinate;
            coords.push(landCoordinate);
            if (coords.length < number) {
                generateRandomLandCoordinates(number,callback);
            } else {
                return callback(coords);
            }
        }
    });
}

Answer №2

It appears that the issue arises when you attempt to execute the '// call geocoder function to check if coordinate is land-based' function.

Error:

Error: unnecessary setTimeout call (missing quotes around argument?)
}), 250);

I don't have the availability to troubleshoot this right now, but here's a simpler example that I've previously used successfully:

if (status == google.maps.GeocoderStatus.OK) { // -- Has a result been returned ?
    DO process stuff
}else{ // -- Location not returned - must be in the sea !
    DO in the sea stuff
}

Perhaps this can provide some assistance ?

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

Implementing Multiple Identification using JavaScript and PHP

I need to complete a simple task. Here is the code snippet: echo' <div class="col-sm-12" id="recensioni_titolo"> <form role="form" id="review-form" method="post" action="php\insert_comment.php"> ...

The magic of $.ajax lies in its ability to load an unexpected URL, diverging from my original

Every time I send a request using an absolute URL, Ajax is posting the wrong URL. For instance, when I request "http://localhost/app/home/session", it mistakenly calls "http://localhost/app/home/home/session" var baseURL = function(link) { var url = & ...

What method can I use to identify the most widely-used edition of a specific npm module?

While the npm registry does provide metrics on the most depended packages, have you ever wondered if it's possible to determine the most popular version of a specific package? For example, as a user considering upgrading to react-router^4.0.0, wouldn ...

Implementing bind to invoke a function during an onClick Event

Here is a code snippet I have been working on that demonstrates how to handle click events on hyperlinks. The code features two hyperlinks named A and B. When hyperlink A is clicked, the console will log 'You selected A', and when B is clicked, ...

Tips for utilizing the "this" keyword in JavaScript in conjunction with the change function

I'm currently facing an issue with the change function. I have two dropdowns that are dependent on each other. Whenever the first dropdown changes, it triggers a change in the second dropdown as well. I achieved this functionality using jQuery AJAX. H ...

The catch all route in Next.js seems to be malfunctioning when paired with the getStaticPaths function

Why is the Next.js catch all route not working as expected with the getStaticPaths function? The documentation states that I should be able to navigate to both t/a.cat and t/a.cat/a.id, but it only seems to work for the latter. What could be causing this ...

Purge all previous page visits within a specified domain upon user logout using JavaScript

On my website, abc.xyz.com, an individual named A logs in from the login page and is directed to the home page. Then, when user A clicks on the profile button, they are taken to a page displaying their information. User A logs out, prompting the site to ...

What is the best way to transform an array of objects into MenuItems for a Material-UI Select component?

I am facing an issue with mapping the values of field choices to create options for an MUI Select field from an array called fieldChoices. Here is how I populate the fieldChoices array: fieldChoices = { choices: filtered_status.map(function (item) { ...

Ways to access the attribute of the element being hovered over

So, I am currently attaching event listeners to an array of elements with the intention that when a specific element is hovered over, it will set a property to the id of that element. However, instead of grabbing the id of the hovered element, it seems to ...

Store Dark Mode preferences in the browser's local storage using React and Material-UI

Is there a way to save the dark mode setting in localStorage? Can this approach be used for storing it? Any suggestions on how to achieve this would be appreciated. Thanks, cheers! function App() { const [darkState, setDarkState] = useState("&qu ...

What is the process for showing a duplicate image in a dialog box once it has been selected on an HTML page?

I am experiencing an issue where the dialog box is displaying when I use the button tag, but not when I use the image tag. Can someone please assist? <img src='image.png' height='200px' widht='200px' id='1'> ...

How can I improve my skills in creating efficient Angular routers?

In my Ionic project, I am dealing with an AngularJS routes file that contains a large number of routes, approximately a hundred. The structure is similar to the one provided below. (function() { 'use strict'; angular.module('applicatio ...

Tips for efficiently handling large Excel files in NodeJS without freezing the user interface

Currently, my NodeJS/Angular/Electron app is utilizing the ExcelJS library to read large Excel files that contain over 10,000 lines. While smaller files are processed smoothly, larger files take between 3.9 and 5 seconds to load, during which time the CSS ...

Utilizing Material UI (mui) 5.0 within an iframe: Tips and tricks

Attempting to display MUI components within an iframe using react portal has resulted in a loss of styling. Despite being rendered within the iframe, MUI components seem to lose their visual appeal when displayed this way. Most resources discussing this is ...

Switch out "FOR" in order to sum up every value within an array

Utilizing Javascript, I have an array defined as follows: counts: [ { id: 1, value: 0 }, { id: 2, value: 10 }, { id: 3, value: 5 }, { id: 4, value: 3 } ] I aim to calculate a variable named total that holds the sum of all valu ...

Including a 3DS card to a Stripe Client for recurring payments

I'm encountering an issue when trying to add payment cards with 3DS authentication for existing customers who already have an active monthly subscription. The objective is to allow our clients to change, remove, and add cards to the Stripe Customer ob ...

Simple Express Path Challenge

I've hit a roadblock in my JavaScript tutorial on Mozilla and could really use some assistance. Below are excerpts from 3 different files: a) In the app.js file, I am trying to locate Router handlers and then present them: //app.js //the fol ...

After 30 to 80 touches, the movement starts to lag and an error appears in the console

Error Details: [Intervention] A touchend event cancellation attempt was ignored due to cancelable=false, likely because scrolling is in progress and cannot be stopped. preventDefault @ jquery.min.js:2 (anonymous) @ number_grid_game.php:239 each @ ...

Having trouble decoding URL in nodeJS

I have encountered an issue while using the express framework in NodeJS. I am attempting to send an activation link via email, but when activating the link, the URL becomes encoded and the express routes are unable to read it, leading to a 404 error page. ...

Angular Dynamic Table Column Adaptor

Recently, I came across the adpt-strap table lite and decided to experiment with it. Here is the JSfiddle link for the project I was working on: http://jsfiddle.net/cx5gm0sa/ My main goal was to dynamically hide or show a column. In my code, I added $scop ...