"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

Effortlessly uploading large files using axios

I am currently facing an issue and I am seeking assistance. My goal is to implement file chunk upload using axios, where each chunk is sent to the server sequentially. However, the requests are not being sent in order as expected. Below is a snippet of m ...

Please provide TypeScript code for a React wrapper function that augments a component's props with two additional functions

During the course of my project, I implemented a function wrapping React component to incorporate undo/redo functionality using keyboard shortcuts Ctrl+Z and Shift+Ctrl+Z. Here is an example: import React from 'react'; interface WithUndoRedoProp ...

Using JavaScript to invoke Applescript commands

Is it feasible to execute Applescript from JavaScript? I would be grateful if someone could offer a sample code or useful reference link. ...

Securely encoding information with PHP and decrypting it using JavaScript

I'm currently working with 2 servers. My goal is to generate a pair of keys, store the private key in local storage, and send the public key to my PHP server. The main objective is to encrypt data using the public key in PHP and decrypt it using Jav ...

Firing ng-change with fileModel or input type="file"

Is there a way to trigger ng-change when a change occurs with this file directive? I have implemented a custom file directive for this purpose. The Directive: app.directive('ngFileModel', ['$parse', function($parse) { return { ...

Stopping a Firefox addon with a button click: A step-by-step guide

Utilizing both the selection API and clipboard API, I have implemented a feature in my addon where data selected by the user is copied to the clipboard directly when a button is clicked (triggering the handleClick function). However, an issue arises when a ...

Unable to produce scrolling animation using JavaScript

I'm trying to implement a feature on my website where the page scrolls with a sliding effect when the user presses the "Scroll" button. However, I've encountered issues as it doesn't seem to work despite adding the necessary tags to my HTML ...

PHP: A guide on validating textboxes with jQuery AJAX

How can I use jQuery AJAX to validate a textbox on focusout? The validation process includes: Sending the value to a PHP page for server-side validation Displaying an alert message based on the validation result I have only impl ...

Unable to retrieve PHP object using AJAX

I am having trouble fetching the PHP file from Ajax. In the PHP file, an object is created and then converted into JSON using the json_encode() function. However, when I try to request that PHP file from Ajax, nothing is displayed as output ('Smith&ap ...

Problem with routing: Request parameters not being collected

I am currently working on a project to create a wikipedia clone. Initially, I set up an edit route that looks like this: router.get('/edit/:id', function(req, res){ var id = req.params.id; console.log(id); models.Page.findById(id, ...

Are the orders of events maintained when emitted using an event emitter?

I have a simple query regarding the event emitter, which is crucial for my program's logic. Currently, I am utilizing an external library that triggers events that I'm listening to. These events consist of 'data' and 'error'. ...

Utilizing AngularJS HotTowel to trigger a spinner when making AJAX requests

I am attempting to trigger the spinner whenever there is an xhr call within the application. Currently, the spinner only appears when clicking on a menu or navigating to a different page. Index page <aside class="main-sidebar"> <!-- ...

Trigger ajax request automatically without the need for a button click

Is there a way to make an AJAX call in jQuery without the need for clicking a button, but rather have it execute when the page loads? This is the button: <div> <form method="post" action=""> <button value="cars" type="submit" i ...

Create a JavaScript function that replicates the behavior of submitting a form when logging

I successfully implemented a logout button that ends sessions established using express server ExpressOIDC/express-session. When the user clicks on the logout button, they are redirected to the logged out view. Here is the HTML for the logout button: &l ...

Locate the parent and child elements within an array

Within the array provided below, there are parent items as well as children. I am currently able to identify parents (depth 0) and their immediate children (depth 1), however I am unsure how to handle deeper nested levels. For reference, you can view the ...

How can AngularJS apps handle authentication?

Seeking input on user authentication with AngularJS and Zend... I currently have Angular on the client side and Zend on the server side handling authentication successfully. However, I'm looking for best practices and code examples for enhancing the ...

Change the color of the menu icon based on the specified HTML class or attribute

I'm trying to create a fixed menu that changes color depending on the background of different sections. Currently, I am using a data-color attribute but I am struggling with removing and adding the class to #open-button. Adding the class works fine, ...

Guide: How to include a date value within a JSON format? [See code snippet below]

Currently, I am developing a react application that includes a form with sections for basic details and employment information. The form is almost completed, and I have successfully structured the data in JSON format for different sections. To see a work ...

The challenge of PHP's HTTP_REFERER

I am experiencing an issue with http_referer. In my setup, I have two files: index.php and index.html. The index.php file contains a form that, upon submission, includes information like the http_referer. On the other hand, the index.html file runs an aja ...

Error message stating that the function "data.map" is not recognized, resulting in a

const ShoppingList = ({ itemList }) => { let { loading, items } = itemList; console.log(items); return ( <div> {loading ? ( <p>Loading...</p> ) : ( <table> <thead> ...