Reputation: 3
I've looked at a few topics that are similar and tried the suggestions but I can't get this to work.
On this page http://www.thefuelcardpeople.co.uk/test-pump-locator/ I've got a button that gets the lat and long coordinates from geo location data, then connects to the https://api.postcodes.io/postcodes API to do a reverse postcode lookup.
I've got it to return the full data string and it shows that, but I can't work out how to then return just the postcode value. I want to prefill a form field input with the postcode value that the API returns from the geolocation data.
Can anyone help with this?
This is my code:
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<p id="demo2"></p>
<pre id="geocode-postcode-result" class="code-box" style="display: block;"></pre>
<script>
var x = document.getElementById("demo");
var y = document.getElementById("demo2");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var lon = position.coords.longitude;
var lon2 = lon.toFixed(14);
var lat = position.coords.latitude;
var lat2 = lat.toFixed(14);
x.innerHTML = "Latitude: " + lat2 + "<br>Longitude: " + lon2;
var $result = jQuery("#geocode-postcode-result");
var displayJsonResult = function ($context, data) {
$context.html(JSON.stringify(data, null, 4)).slideDown();
}
jQuery.get("https://api.postcodes.io/postcodes?lon=" + lon2 + "&lat=" + lat2 + "&limit=1")
.done(function (data) {
displayJsonResult($result, data);
})
.fail(function (error) {
displayJsonResult($result, error.responseJSON);
});
}
</script>
Thanks for the reply - the response that gets written is:
{
"status": 200,
"result": [
{
"postcode": "BB11 2DB",
"quality": 1,
"eastings": 384278,
"northings": 432561,
"country": "England",
"nhs_ha": "North West",
"longitude": -2.2401189327649,
"latitude": 53.7891288271951,
"parliamentary_constituency": "Burnley",
"european_electoral_region": "North West",
"primary_care_trust": "East Lancashire Teaching",
"region": "North West",
"lsoa": "Burnley 003D",
"msoa": "Burnley 003",
"incode": "2DB",
"outcode": "BB11",
"distance": 30.904269682,
"admin_district": "Burnley",
"parish": "Burnley, unparished area",
"admin_county": "Lancashire",
"admin_ward": "Daneshouse with Stoneyholme",
"ccg": "NHS East Lancashire",
"nuts": "East Lancashire",
"codes": {
"admin_district": "E07000117",
"admin_county": "E10000017",
"admin_ward": "E05005155",
"parish": "E43000093",
"ccg": "E38000050",
"nuts": "UKD46"
}
}
]
}
Upvotes: 0
Views: 721
Reputation: 3435
Assuming that the string you have given is the entirety of the data
returned in the call, you would simply do:
data.result[0].postcode
This will get you a string representing just the postcode, which you can use however you please.
Upvotes: 1