Skip to content

Commit 5e8c57c

Browse files
committed
finished city drop down bit
1 parent ad7806e commit 5e8c57c

File tree

1 file changed

+63
-3
lines changed

1 file changed

+63
-3
lines changed

06 - Type Ahead/index-START.html

Lines changed: 63 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,72 @@
1010
<form class="search-form">
1111
<input type="text" class="search" placeholder="City or State">
1212
<ul class="suggestions">
13-
<li>Filter for a city</li>
14-
<li>or a state</li>
13+
<li>Filter by city</li>
14+
<li>or state</li>
1515
</ul>
1616
</form>
1717
<script>
18-
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
18+
var endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
19+
var places = [];
20+
var suggestions = document.querySelector('.suggestions');
21+
var search = document.querySelector('.search');
22+
var lat = -999;
23+
var lon = -999;
24+
var hasPosi = false;
25+
26+
fetch(endpoint)
27+
.then(function(blob) {return blob.json();})
28+
.then(function(data) {places = data;})
29+
30+
function positionFound(position) {
31+
lat = position.coords.latitude;
32+
lon = position.coords.longitude;
33+
hasPosi = true;
34+
}
35+
36+
var findMatches = function(word, place) {
37+
var giRegex = new RegExp(word, 'gi');
38+
return place.city.match(giRegex) || place.state.match(giRegex);
39+
}
40+
41+
var sortMatches = function(matches) {
42+
if (hasPosi) {
43+
matches.sort(function(m1, m2){
44+
return (Math.sqrt(Math.pow((m1.latitude - lat), 2)) +
45+
Math.sqrt(Math.pow((m1.longitude - lon), 2))) >
46+
(Math.sqrt(Math.pow((m2.latitude - lat), 2)) +
47+
Math.sqrt(Math.pow((m2.longitude - lon), 2)));
48+
})
49+
} else {
50+
matches.sort(function(m1, m2){
51+
return m1.city > m2.city;
52+
});
53+
}
54+
return matches;
55+
};
56+
57+
var doSearch = function(){
58+
var word = document.querySelector('.search').value;
59+
if (word.length < 1) {
60+
suggestions.innerHTML = '<li>Filter by city</li><li>or state</li>';
61+
return;
62+
}
63+
var matches = places.filter(function(place){
64+
return findMatches(word, place);
65+
});
66+
matches = sortMatches(matches);
67+
var suggestText = '';
68+
matches.forEach(function(match){
69+
suggestText += '<li>' + match.city + ', ' + match.state + '</li>';
70+
});
71+
suggestions.innerHTML = suggestText;
72+
}
73+
74+
search.addEventListener('change', doSearch);
75+
search.addEventListener('keyup', doSearch);
76+
if (navigator.geolocation) {
77+
navigator.geolocation.getCurrentPosition(positionFound);
78+
}
1979

2080
</script>
2181
</body>

0 commit comments

Comments
 (0)