"Mastering the Geocoder Class: Unleashing the Power of AJAX for Latitude and Longitude Retrie

This JSON array includes a collection of addresses

[
{
"id": 0,
"title": "Coop.Sociale Prassi e Ricerca Onlus", 
"latitude": 0,
"longitude": 0,
"address": "Viale Eleonora D'Arborea 12, Roma, IT"
},
{
"id": 0,
"title": "San Lorenzo",
"latitude": 0,
"longitude": 0,
"address": "Viale della Primavera 330, Roma, IT"
},
{
"id": 0,
"title": "Giardinetti",
"latitude": 0,
"longitude": 0,
"address": "Via Molfetta 45, Roma, IT"
},
{
"id": 0,
"title": "Montesacro",
"latitude": 0,
"longitude": 0,
"address": "Viale Parioli, Roma, IT"
},
{
"id": 0,
"title": "Casa",
"latitude": 0,
"longitude": 0,
"address": "Piazza Vescovio, Roma, IT"
}
]

Using JavaScript, this file loads the JSON array asynchronously. It contains a list of addresses with corresponding latitude and longitude values that are obtained through an AJAX request. The function codeAddress converts the address to latitude and longitude.

var geocoder;
var map;
var arr = [];
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(41.90832, 12.52407);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyD3Xz7-z7U_XzZiaOlx9khhtFSld8vd0k4' +
'&signed_in=true&callback=initialize';
document.body.appendChild(script);
}

window.onload = loadScript;

var xmlhttp = new XMLHttpRequest();
var url = "json/array.json";

xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
arr = JSON.parse(response);
function codeAddress(x) {
var address = arr[x].address;
console.log(arr[x].address);
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
arr[x].latitude = results[0].geometry.location.A;
console.log(arr[x].latitude);
arr[x].longitude = results[0].geometry.location.F;
console.log(arr[x].longitude);
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
function myLoop() {
for (i = 0; i < arr.length; i++) {
codeAddress(i);
console.log(arr[i].address);
}  
}
 html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Geocoding service</title>
<script src="js/geocode_ajax.js"></script>
</head>
<body>
<div id="panel">
<input id="address" type="textbox" value="Roma, IT">
<input type="button" value="Geocode" onclick="myLoop()">
</div>
<div id="map-canvas"></div>
</body>
</html>

An error message stating 'codeAddress is not defined' has been returned

Answer №1

Due to the scope of your codeAddress JavaScript function being enclosed within myFunction, it is not accessible by the outer caller myLoop. This results in the error message codeAddress is not defined.

To resolve this issue, you can consider restructuring your code as shown below (please note that this code is provided for demonstration purposes and might require testing and adjustments):


var geocoder;
var map;
var arr = [];

function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(41.90832, 12.52407);
  var mapOptions = {
    zoom: 8,
    center: latlng
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyD3Xz7-z7U_XzZiaOlx9khhtFSld8vd0k4' +
      '&signed_in=true&callback=initialize';
  document.body.appendChild(script);
}

window.onload = loadScript;

var xmlhttp = new XMLHttpRequest();
var url = "json/array.json";
var arr;

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        arr = JSON.parse(xmlhttp.responseText);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function codeAddress(x) {
  var address = arr[x].address;
  console.log(arr[x].address);
  geocoder.geocode({ 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      arr[x].latitude = results[0].geometry.location.A;
      console.log(arr[x].latitude);
      arr[x].longitude = results[0].geometry.location.F;
      console.log(arr[x].longitude);
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

function myLoop() {
  for (i = 0; i < arr.length; i++) {
    codeAddress(i);
    console.log(arr[i].address);
  }  
}

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

Merging two arrays concurrently in Angular 7

When attempting to merge two arrays side by side, I followed the procedure below but encountered the following error: Cannot set Property "account" of undefined. This is the code in question: acs = [ { "account": "Cash In Hand", ...

Discovering intersection points along a line between the previous and current positions of the mouse in Three.js

I am working on a project in Three.js where I have a scene filled with lines. Everything is working smoothly when the mouse moves slowly, as I am using the raycaster method to check for intersections with the lines. However, the issue arises when the mouse ...

The try and catch block in JavaScript is failing to correctly capture the HTTP status

I have a function that successfully posts JSON to an API endpoint. Here is the code I am using: function sendValuesPageLoad(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { try { if (xhr.readyState === ...

Whenever AJAX is employed, PHP validation consistently presents an error or false outcome, regardless of the conditions being

I have a dilemma with my form. There are only two conditions: If the yourname field is empty, it should return an error. If the email field is empty, it should also return an error. However, I am getting an error even when both fields are not empty. I cann ...

I'm intrigued: what type of syntax is Facebook's polling service utilizing in the callback?

While monitoring the Network Monitor on Chrome's developer tool, I observed how Facebook updates content on their news feed. All AJAX responses start with the following: for (;;);{"__ar":1,"payload":[]} I'm curious about what the for(;;); piec ...

I'm having some trouble with my middleware test in Jest - what could be going wrong?

Below is the middleware function that needs testing: export default function validateReqBodyMiddleware(req: Request, res: Response, next: NextFunction) { const { name, email }: RequestBody = req.body; let errors: iError[] = []; if (!validator.isEmai ...

The issue persists with the JavaScript window.location script constantly refreshing

I am currently working on a small web application where I want to update 2 parameters in the URL using Javascript. However, every time I use "window.location.search = 'scene.html?name=' + person + '&scene=' + readCookie("scene");", ...

Generating a component and rendering it according to the dynamic route parameters using mapStateToProps and reselect techniques

I have set up a global app container to store data for different rooms, with a sub-container called roomDetails that utilizes a reselect selector to pick a room from the global state based on ownProps.params.slug. This process is accomplished through mapSt ...

The most recent version of Autonumeric now permits the inclusion of a decimal point, even if the decimalPlaces parameter

I need to ensure that only whole numbers are allowed in the input textboxes, while also displaying a currency symbol and commas. I am using the most recent version of Autonumeric JS for this purpose. Even after setting the decimalPlaces property to 0, I a ...

Concealing Contact Form Using Javascript

Upon making adjustments to a website, I encountered an issue with the contact form. The form is meant to be hidden on page load and only appear when the envelope icon is clicked. However, currently the form is visible by default, and clicking the envelope ...

Verifying Angular (2+?) Compatibility: Opening and Closing Material mat-menu on Hover [GUIDE]

After extensive research, I tried various methods to hover a material menu to display its options. However, the solutions I came across were either too complicated or ineffective. Therefore, I decided to develop my own solution by combining elements of e ...

Querying with Codeigniter in Ajax Data table only returns a single row

When using codeigniter to create an ajax data-table, I pass the User ID as a condition to retrieve records from a product orders table. $this->datatables->select('orders.order_user_id,orders.order_date,orders.order_id,orders.order_confirmation_ ...

The edges of shapes created with ThreeJs appear to have a fuzzy or blurred outline

Trying to create a cube in ThreeJs using Box Geometry, but encountering strange and shaky lines. Even setting wireframe to false doesn't resolve the issue, as the edges remain problematic. https://i.sstatic.net/sUPAX.png Currently utilizing WebGlRen ...

Creating a test suite with Jasmine for an Angular ui-grid component compiled without using $scope

I have encountered an issue while using $compile to compile a ui-grid for Jasmine testing. Initially, everything worked smoothly when I passed $scope as a parameter to the controller. However, I am now transitioning to using vm, which has resulted in $comp ...

Adjusting specific sections of a container in real-time

Fiddle: https://jsfiddle.net/1b81gv7q/ Sorry for the slightly cryptic title; I couldn't come up with a better way to phrase it. Imagine this scenario: there's a container with content that needs to be dynamically replaced. If I wanted to repla ...

Mastering Light and Camera Selection in Three.js

Question, In the editor found at this link, you can click on a light or camera to select it. I am familiar with using raycaster.intersectObjects(objects) to select meshes, but how can I achieve the same result for lights and cameras which do not have mesh ...

AJAX list refresh, fetch additional items and tally

Looking for a solution to update the values of listUsernames and numUsernames after adding an item? Check out this scenario: <ul id='usernameList'> <li class='username'>John</li> <li class='username&apo ...

How can I efficiently create a suffix using this JavaScript code?

Take note that the code displayed below showcases the array in the console, rather than in the snippet output var names = ["maria", "mary", "marks", "michael"]; function add_suffix(names) { var suffixes = []; for (var i = 0; i < names.length; i+ ...

Is it possible to remove the browsing history of user inputs in JavaScript?

I'm currently working on a Simon Says game where the level of difficulty increases as players correctly repeat the pattern. However, I encountered an issue with clearing the input history that shows previous patterns entered by the user. How can I res ...

An issue occurred during the project compilation using npm

My project installation process is giving me some trouble. Initially, when I run npm install, it successfully installs all the dependencies. However, when I proceed to execute npm run compile, I encounter an error. Below is the log file for a better under ...