My code is below. This is for a Google Map where you click a spot on the map and it shows in a left pane info from the point of the click. I want to use the lattitude and longitude in my Javascript to do other processing. I see the code returns an object, and when I open it via clicking on it in the Console Log I can see the data that the object contains. I can’t seem to open the object with Javascript to read data from it. I am trying to do this near "alert(response);" in my code. I have read solutions on the internet but none have produced anything but blanks while I can see a lot of data by manually reviewing the Console after I click. Thanks for the help!
<!DOCTYPE html>
<!--
@license
Copyright 2019 Google LLC. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
-->
<html>
<head>
<title>Geocoding Service</title>
<script>
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
let map;
let marker;
let geocoder;
let responseDiv;
let response;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
zoom: 7,
center: { lat: 44.630978, lng: -86.072480 },
mapTypeControl: false,
});
geocoder = new google.maps.Geocoder();
const inputText = document.createElement("input");
inputText.type = "text";
inputText.placeholder = "Enter a location";
const submitButton = document.createElement("input");
submitButton.type = "button";
submitButton.value = "Geocode";
submitButton.classList.add("button", "button-primary");
const clearButton = document.createElement("input");
clearButton.type = "button";
clearButton.value = "Clear";
clearButton.classList.add("button", "button-secondary");
response = document.createElement("pre");
response.id = "response";
response.innerText = "";
responseDiv = document.createElement("div");
responseDiv.id = "response-container";
responseDiv.appendChild(response);
const instructionsElement = document.createElement("p");
instructionsElement.id = "instructions";
instructionsElement.innerHTML =
"<strong>Instructions</strong>: Enter an address in the textbox to geocode or click on the map to reverse geocode.";
map.controls[google.maps.ControlPosition.TOP_LEFT].push(inputText);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(submitButton);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(clearButton);
map.controls[google.maps.ControlPosition.LEFT_TOP].push(
instructionsElement
);
map.controls[google.maps.ControlPosition.LEFT_TOP].push(responseDiv);
marker = new google.maps.Marker({
map,
});
map.addListener("click", (e) => {
geocode({ location: e.latLng });
});
submitButton.addEventListener("click", () =>
geocode({ address: inputText.value })
);
clearButton.addEventListener("click", () => {
clear();
});
clear();
}
function clear() {
marker.setMap(null);
}
function geocode(request) {
clear();
geocoder
.geocode(request)
.then((result) => {
const { results } = result;
map.setCenter(results[0].geometry.location);
marker.setPosition(results[0].geometry.location);
marker.setMap(map);
response.innerText = JSON.stringify(result, null, 2);
return results;
})
.catch((e) => {
alert("Geocode was not successful for the following reason: " + e);
});
alert(response);
console.log("response =");
console.log(response);
function readPreElement() {
const preElement = document.getElementById("response"); // Replace "myPre" with the ID of your <pre> element
const textContent = preElement.textContent;
console.log("text content = " + textContent); // Output the content to the console
// You can do whatever you want with the textContent here
}
readPreElement();
// const preElement = document.getElementById("response");
// const content = preElement.textContent;
// console.log("content = " + content);
var _html = document.getElementsByTagName('pre')[0].innerHTML;
console.log("_html = " + _html);
alert("_html is type: " + typeof(_html));
alert("_html is length of: " + _html.length);
var _query = document.querySelector('pre').innerHTML;
console.log(_query);
alert("_query is type: " + typeof(_query));
alert("_query is length of: " + _query.length);
//alert(typeof(map));
//alert(response.innerText.length);
//console.log(map);
//report_it();
}
window.initMap = initMap;
</script>
<style>
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Always set the map height explicitly to define the size of the div element
* that contains the map.
*/
#map {
height: 50%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
input[type="text"] {
background-color: #fff;
border: 0;
border-radius: 2px;
box-shadow: 0 1px 4px -1px rgba(0, 0, 0, 0.3);
margin: 10px;
padding: 0 0.5em;
font: 400 18px Roboto, Arial, sans-serif;
overflow: hidden;
line-height: 40px;
margin-right: 0;
min-width: 25%;
}
input[type="button"] {
background-color: #fff;
border: 0;
border-radius: 2px;
box-shadow: 0 1px 4px -1px rgba(0, 0, 0, 0.3);
margin: 10px;
padding: 0 0.5em;
font: 400 18px Roboto, Arial, sans-serif;
overflow: hidden;
height: 40px;
cursor: pointer;
margin-left: 5px;
}
input[type="button"]:hover {
background: rgb(235, 235, 235);
}
input[type="button"].button-primary {
background-color: #1a73e8;
color: white;
}
input[type="button"].button-primary:hover {
background-color: #1765cc;
}
input[type="button"].button-secondary {
background-color: white;
color: #1a73e8;
}
input[type="button"].button-secondary:hover {
background-color: #d2e3fc;
}
#response-container {
background-color: #fff;
border: 0;
border-radius: 2px;
box-shadow: 0 1px 4px -1px rgba(0, 0, 0, 0.3);
margin: 10px;
padding: 0 0.5em;
font: 400 18px Roboto, Arial, sans-serif;
overflow: hidden;
overflow: auto;
max-height: 50%;
max-width: 90%;
background-color: rgba(255, 255, 255, 0.95);
font-size: small;
}
#instructions {
background-color: #fff;
border: 0;
border-radius: 2px;
box-shadow: 0 1px 4px -1px rgba(0, 0, 0, 0.3);
margin: 10px;
padding: 0 0.5em;
font: 400 18px Roboto, Arial, sans-serif;
overflow: hidden;
padding: 1rem;
font-size: medium;
}
</style>
</head>
<body>
<div id="map"></div>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBxeRjDvCOd2QP-12ayt-vg1YZ71WPcwSk&callback=initMap&v=weekly&solution_channel=GMP_CCS_geocodingservice_v2"
defer
></script>
<script src="final_NWS.js">
</script>;
<div id="profile">
temperatureString;
</div>
</body>
</html>
2
Answers
The issue in this is, how to extract the latitude and longitude from the result object returned by the geocode function. The response object is being set as the inner text of a
function geocode(request) {
clear();
geocoder.geocode(request).then((result) => {
const { results } = result;
if (results.length > 0) {
const location = results[0].geometry.location;
const lat = location.lat(); // Get latitude
const lng = location.lng(); // Get longitude
// Update the map and marker
map.setCenter(location);
marker.setPosition(location);
marker.setMap(map);
// Display response in the <pre> tag
response.innerText = JSON.stringify(result, null, 2);
// Log the lat and lng for further processing
console.log("Latitude:", lat);
console.log("Longitude:", lng);
// Use lat and lng for other processing
alert(`Latitude: ${lat}, Longitude: ${lng}`);
} else {
alert("No results found!");
}
return results;
})
.catch((e) => {
alert("Geocode was not successful for the following reason: " + e);
});
}
lets focus on just the thing you’re trying to understand:
response is an HTML element "document.createElement("pre")" not an object
.then((result) result is the "response" object
.then((result) is a resolver of a promise you cannot access ‘result’ outside of the promise chain
heres your confusing part
because the alert is outside of the promise chain it has alerted before the response was completed so it has nothing in it yet.
put the alert inside the promise chain and you’ll soon see whats going on
last tip is to consider learning the syntax for async await, it makes this type of task much easier to read