|
10 | 10 | <form class="search-form">
|
11 | 11 | <input type="text" class="search" placeholder="City or State">
|
12 | 12 | <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> |
15 | 15 | </ul>
|
16 | 16 | </form>
|
17 | 17 | <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 | +} |
19 | 79 |
|
20 | 80 | </script>
|
21 | 81 | </body>
|
|
0 commit comments