I have 2 functions getLocation() and getLocationName().
The getLocation() function executes an XMLHttpRequest and I wish to pass the response to the getLocationName() function in order to display it in a list.
getLocationName = (location) => {
var locName = location;
console.log("location name", locName)
return locName;
}
getLocation = (lat, lon) => {
var text;
var xmlhttp = new XMLHttpRequest();
var url = "https://nominatim.openstreetmap.org/search?format=jsonv2&accept-language=sr-Latn&limit=3&q=" + lat + "," + lon;
console.log("url: ", url)
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
var resp = JSON.parse(this.responseText);
text = resp[0].display_name;
console.log("response: ", text);
this.getLocationName(text);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
I can see the response in the console.log() from getLocation, but I get
Uncaught TypeError: this.getLocationName is not a function
I tried calling it without "this." tried to bind it in the constructor like this
constructor(props){
super(props);
this.getLocationName = this.getLocationName.bind(this);
}
Also tried calling it this way:
() => this.getLocationName(text);
No luck unfortunately...
Yes. This is about 'this'. "xmlhttp" object has its own 'this'. Try this:
getLocation = (lat, lon) => {
var that = this; //save this
var text;
var xmlhttp = new XMLHttpRequest();
var url = "https://nominatim.openstreetmap.org/search?format=jsonv2&accept-language=sr-Latn&limit=3&q=" + lat + "," + lon;
console.log("url: ", url)
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
var resp = JSON.parse(this.responseText);
text = resp[0].display_name;
console.log("response: ", text);
that.getLocationName(text);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments