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

Tips for extracting the image URL from my JSON string

I am in possession of a json file that includes URLs for images, and I have come across something that seems to be a URL, which is encoded as: iVBORw0KGgoAAAANSUhEUgAAADYAAAAzCAMAAADrVgtcAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6m ...

How to pass a variable or value through the async await API in the Vue.js and Laravel integration?

I'm facing an issue with my API where I want to check if a given email exists in the database, but every time I run it and view the console log, it returns undefined. Can anyone here suggest a better code snippet or approach for this? I specifically w ...

Facing problem with implementing NgMoudleFactoryLoader for lazy loading in Angular 8

A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments: angular.json "architect": { "build": { ... "options": { ... "lazyM ...

Using "array_agg" in a "having clause" with Sequelize

I am facing a particular scenario with my database setup. I have three tables named computers, flags, and computerFlags that establish relationships between them. The structure of the computerFlags table is as follows: computerName | flagId computer1 | ...

Transferring an Array from PHP to Javascript

I'm attempting to pass a PHP array so that I can use it in JavaScript. The PHP code I have written is shown below: <?php $link = mysqli_connect("localhost", "root", "password", "database"); /* check connection */ if (mysqli_connect_errn ...

Retrieve text from the input field after a brief pause following each keystroke for uninterrupted typing

I am currently facing an issue with a form that is submitted remotely whenever the elements change. Specifically, when a user types in the search field and hits a key, the form gets submitted multiple times even though only the final submission matters. I ...

Resolve Redux-Firestore issue #45: Possible Solutions?

I'm facing an issue where deleting a document from Firestore results in my Redux store showing it as null instead of removing it. Even though the document is deleted in Firestore, this inconsistency causes frontend issues because my .map functions can ...

What is the best way for my web application to interface with a serial port?

I am working on a cloud-based web application that uses ASP Web API and Angular, both hosted on Azure. I have a requirement for my Angular app to communicate with a serial port for reading and writing data. How can I achieve this functionality? I've ...

Tips on incorporating JavaScript files into Angular applications

Struggling to incorporate a JavaScript function into Angular, I have installed the plugin "npm I global payments-3ds". I copied the JavaScript files from node_modules and attempted to call them in my component. Below is an example: import { ...

Having difficulty maintaining trailing zeroes in decimals after converting to float in Angular

I need assistance with converting a string to float in Angular. Whenever I use parseFloat, it seems to remove the zeros from the decimal values. How can I ensure that these zeros are retained with the numerical values? The example below should provide more ...

jQuery divs seem to "gaze up" towards the mouse pointer

I am attempting to recreate a fascinating effect using jQuery - where "cards" move in response to the mouse cursor as if they are looking up at it. I have come across a script that almost achieves what I need, but I require the ability to control the mov ...

Difficulty in toggling on and off several form elements with JavaScript

Trying to control multiple form elements on an HTML page with JavaScript has presented a challenge for me. In my form, each row contains a checkbox that should enable/disable the elements on that row. The issue I'm facing is that only the first two f ...

Creating an identifier for the jQuery slideToggle function involves assigning a unique class or ID to

I am currently working on creating an identifier for the jQuery slide.Toggle function. In my PHP code, I have a loop that prints values, each with a button and a div that should be able to slide toggle. So far in PHP, here is what I have attempted, withou ...

What are some ways to conceal methods within a class so that they are not accessible outside of the constructor

I am a newcomer to classes and I have written the following code: class BoardTypeResponse { created_on: string; name: string; threads: string[]; updated_on: string; _id: string; delete_password: string; loading: BoardLoadingType; error: Bo ...

How can I use jQuery to switch the positions of two <div> elements in HTML based on the selection of a dropdown value?

I need to switch the display positions of two <div> containers based on a dropdown value change. Can this be accomplished using jQuery? Here are the two div containers whose display positions need to be interchanged: <div id="first"><p> ...

Expanding the outer div with Jquery's append() function to accommodate the inner div elements perfectly

I am facing an issue where my outer div does not expand automatically to fit the elements I append inside it using jQuery. The structure of my div is as follows: <div class="well" id='expand'> <div class="container"> < ...

Utilize the same variable within a React functional component across multiple components

Within a React functional component, I am utilizing the following constant: const superHeroPowers = [ { name: 'Superman', status: superManPowerList }, { name: 'Batman', status: batmanPowerList }, { name: 'Wonder Woman&a ...

A plethora of color choices in a Multi-select Box

Hi there! I am facing an issue with dynamically adding multiple select boxes. Currently, I have 4 color-coded options under the selection boxes, which work fine when there is only one box. However, when I add more than one select box, the color coding doe ...

When I click on the md-select element, a superfluous "overflow-y: scroll;" gets added to the <body> of my webpage

Typically, I have the following styles on my body: element.style { -webkit-app-region: drag; } However, when I interact with a md-select element (you can observe this behavior on the provided link), additional styles are applied. element.style { -w ...

What is the predefined value for a multi-select generated by the ng-for directive in Angular?

I am having trouble setting default selected values for the multi-select. Despite trying various methods such as initializing the ngModel to bind the variable and using [selected] = "selectedSegment == 'S1'", none of them seem to be effective fo ...