I am looking to filter the elements of a select list according to latitude and longitude coordinates.
Indeed, I would like to display the 10 nearest cities according to a postal code. This is my form : https://jsfiddle.net/mycreatz/zhorw4qc/
In the first field, enter a postal code (example of French postal codes: 78310, 76110). In the second field, we display the name of the city and we get its coordinates (lat + lng). In the third field, I would like to filter the list according to the coordinates of the city to display the 10 closest results.
<input type="number" placeholder="Code Postal" autocomplete="off" pattern="[0-9]{5}" maxlength="5" name="code_postal" id="code_postal" />
<input name="city" list="output" maxlength="100" type="text" placeholder="Ville" autocomplete="off" id="city" list="output" />
<datalist id="output">
</datalist>
<select id="filter" name="filter" >
<option value="0" selected="" disabled="">Séléctionnez ville</option>
<option value="city__0" data-lat="46.18330317" data-lng="5.20548105 ">01960 - Ville n°1</option>
<option value="city__2" data-lat="49.5785983" data-lng="3.65402699 ">02000 - Ville n°3</option>
<option value="city__4" data-lat="49.84820447" data-lng="3.2701833 ">02100 - Ville n°5</option>
<option value="city__6" data-lat="49.3622495" data-lng="3.3264193 ">02200 - Ville n°7</option>
<option value="city__8" data-lat="46.13107447" data-lng="3.42756482 ">03200 - Ville n°9</option>
<option value="city__10" data-lat="43.82125316" data-lng="5.7939841 ">04100 - Ville n°11</option>
</select>
JQUERY CODE :
$(function() {
// OnKeyDown Function
$("#code_postal").keyup(function() {
var zip_in = $(this);
if ((zip_in.val().length == 5)) {
// Make HTTP Request
$.ajax({
url: "//api-adresse.data.gouv.fr/search/?q=" + zip_in.val() + "&type=municipality&limit=30",
cache: false,
dataType: "json",
type: "GET",
success: function(result, success) {
suggestions = [];
for (ii in result['features']) {
//city name + lat + lng
suggestions.push([result['features'][ii]['properties']['name'], result['features'][ii]['geometry']['coordinates'][0], result['features'][ii]['geometry']['coordinates'][1]]);
// console.log(suggestions);
}
jQuery.each(suggestions, function(i, val) {
console.log(val);
$("#output").append("<option value=\"" + val[0] + "\" data-lat=\"" + val[2] + "\" data-lng=\"" + val[1] + "\">");
});
},
});
}
});
});