Hi,
I have the following code that autocompletes an address then returns using Bing API. Once the user selects the address, the longitude is sent to an input field. Everything works, but I am running into issues when implementing the code in fields that are in a collection. Whenever I add a new “set” in the collection, I was able to get the “address input” to be unique per set, but the coordinates field value is set to the new search in every “latitude” field. I am sure there is an issue with my JavaScript code. A possible solution to this is to send separate request to the API, but since I am trying to limit the number of calls to the API, I am hoping to avoid this.
The reason I need the coordinates is because I use those values in a separate API search to calculate the distance between two address. The form I am building is a mileage reimbursement form that automatically calculates the reimbursement amount base on where the employee went.
Below is the code I am using to autocomplete the address, it’s a portion of the code. For obvious reasons I have removed the api key from the code.
Bing rest api= https://docs.microsoft.com/en-us/bingmaps/rest-services/
Any help with this would be greatly appreciated.
$(document).ready(function(){
$('.travelInfoCollection').on('blur', 'input', addressAutoComplete);
function addressAutoComplete(){
$('.addressInput1 input').each(function () {
var objSet = $(this);
objSet.autocomplete({
source: function (request, response) {
$.ajax({
url: "https://dev.virtualearth.net/REST/v1/Locations",
dataType: "jsonp",
data: {
key: "<API KEY GOES HERE>",
q: request.term
},
jsonp: "jsonp",
success: function (data) {
var result = data.resourceSets[0];
if (result) {
if (result.estimatedTotal > 0) {
response($.map(result.resources, function (item) {
return {
data: item,
label: item.name + ' (' + item.address.countryRegion + ')',
value: item.name + ' (Latitude: ' + item.point.coordinates[0] + ' Longitude: ' + item.point.coordinates[1] + ')'
}
}));
}
}
}
});
},
minLength: 1,
change: function (event, ui) {
if (!ui.item)
objSet.val('');
},
select: function (event, ui) {
displaySelectedItem1(ui.item.data);
}
});
function displaySelectedItem1(item) {
$('.fromLat input').val(item.point.coordinates[0]);
}
});
}
});