I'm new on StackOverflow :)
I need help: I'm trying to make an inverse geocode (get an address from coordinates). I have a good URL that works with an ajax. I have many coordinates to convert to address, that is why I'm trying firstly on an array with 4 coordinates on JSfiddle.
What I want for the result is that my script adds all the addresses to my array. I'm trying with a for loop, and on each element of the array, an ajax call which finds the good coordinates.
You can find the call on this link (i put the script after the link) : https://jsfiddle.net/e2wr3umy/
my code which works for an element:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
$.ajax({
url: 'https://reverse.geocoder.ls.hereapi.com/6.2/reversegeocode.json',
type: 'GET',
dataType: 'jsonp',
jsonp: 'jsoncallback',
data: {
prox: '43.564624, 3.847154,250',
mode: 'retrieveAddresses',
maxresults: '1',
gen: '9',
apiKey: 'NOT_THE_REAL_API_KEY'
},
success: function (data) {
var re = JSON.stringify(data);
console.log(data);
var num = (data.Response.View[0].Result[0].Location.Address.HouseNumber);
var rue = (data.Response.View[0].Result[0].Location.Address.Street);
var ville = (data.Response.View[0].Result[0].Location.Address.City);
var CP = (data.Response.View[0].Result[0].Location.Address.PostalCode);
console.log(num, rue, CP, ville)
}
});
Then, I'm trying on an array of 4 elements, this is the link: https://jsfiddle.net/L07pjwba/
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
var adresse = [['43.564624, 3.847154',1],['43.564624, 3.447154',27],['43.64624, 3.727154',75],['43.564624, 3.617154',254]];
for (i =0; i<adresse.length; i++) {
console.log("element", adresse[i]);
$.ajax({
url: 'https://reverse.geocoder.ls.hereapi.com/6.2/reversegeocode.json',
type: 'GET',
dataType: 'jsonp',
jsonp: 'jsoncallback',
data: {
prox: adresse[i][0].concat(', 250'),
mode: 'retrieveAddresses',
maxresults: '1',
gen: '9',
apiKey: 'NOT_THE_REAL_API_KEY'
},
success: function (data) {
var re = JSON.stringify(data);
console.log("data", data);
var num = (data.Response.View[0].Result[0].Location.Address.HouseNumber);
var rue = (data.Response.View[0].Result[0].Location.Address.Street);
var ville = (data.Response.View[0].Result[0].Location.Address.City);
var CP = (data.Response.View[0].Result[0].Location.Address.PostalCode);
adresse[i].push(num, rue, ville, CP);
}
});
}
console.log("adresse : ",adresse);
But the result is not what I expect: it looks like the ajax call starts after the end of the for loop, even if it is inside the for a loop. I tried with async: false
in the ajax, but it didn't change anything.