First thing first, I am new to Javascript and coding so if my code isn’t as tidy or succinct as it could be then please feel free to suggest ways to tidy it up.
I have seen a few similar questions to this topic but nothing that does what I specifically need.
I have a JS code that works nicely that takes a JSON input and returns a specific value:
var subtitle = document.getElementById("demo");
var title = document.getElementById("title_location");
var para1 = document.getElementById("para1");
navigator.geolocation.getCurrentPosition(showPosition);
function showPosition(position) {
var url = "https://api.opencagedata.com/geocode/v1/json?q=52.773322+-1.552661&key=592431a9da4a45b686bc75eafb005cc1" //Swadlincote (already a city so doesnt need replacing)
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data)
console.log(data.results[0].components)
var stringified = JSON.stringify(data);
console.log("this is the stringified json before replacement: " + stringified)
stringifiedR = stringified.replace('"town"', '"city"');
console.log("this is the stringified json after replacement: " + stringifiedR)
var jsonObject = JSON.parse(stringifiedR);
console.log(jsonObject)
console.log("stringified city: : " + jsonObject.results[0].components.city)
subtitle.innerHTML = "Subtitle goes here: " + jsonObject.results[0].components.city
title.innerHTML = "Page Title Goes Here: " + jsonObject.results[0].components.city
para1.innerHTML = "1st paragraph of text goes here: " + jsonObject.results[0].components.city
})
}
This works nicely and returns the value from data.results[0].components.city which is what I need.
What I am looking for is a way to check if the ‘country’ tag in data.results[0].components.country matches “United Kingdom” before I do anything with the script and if the data matches, proceed with the rest of the script, if the ‘country’ tag matches anything other than ‘United Kingdom’ then stop the script.
Does anybody have any ideas they would be happy to share.
Thanks in advance: