$(document).ready(function() { var map, infowindow, querySearch, address, useSideSearch = false, pyrmont, mapZoom = 14, places = {}, cachedPlaces = {}; getGeoLocation(); function getGeoLocation() { const url = 'https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyAytr024G7F4gULgAW1eMTtExZjaFwJuzE'; $.ajax({ url, method: 'POST', }).done(response => { const { lat, lng } = response.location; initMap(lat, lng); }).fail(error => { alert("Cannot detect your location"); }); } function initMap(lat, lng) { pyrmont = new google.maps.LatLng(lat, lng); map = new google.maps.Map(document.getElementById('map'), { center: pyrmont, zoom: mapZoom, }); const defaultBounds = new google.maps.LatLngBounds( new google.maps.LatLng(lat, lng), new google.maps.LatLng(lat, lng)); const input = document.getElementById('search-query'); const options = { bounds: defaultBounds, }; autocomplete = new google.maps.places.Autocomplete(input, options); } $('.main-button, .sidenav-button').on("click", function() { if ($("#search-query").val() === '' || (useSideSearch && $("#sidenav-query").val() === '')) { return; } $(".search-container").hide(); $(".results-list").empty(); querySearch = $('#search-query').val(); if (useSideSearch) { querySearch = $("#sidenav-query").val(); } map = new google.maps.Map(document.getElementById('map'), { center: pyrmont, zoom: mapZoom, }); const request = { location: pyrmont, radius: '10', query: querySearch, }; if (cachedPlaces[querySearch]) { cachePlaces(); } else { infowindow = new google.maps.InfoWindow(); const service = new google.maps.places.PlacesService(map); service.textSearch(request, callback); } function cachePlaces() { const foundPlaces = cachedPlaces[querySearch]; const placesLength = foundPlaces.length; places = {}; for (let i = 0; i < placesLength; i++) { const { place_id } = foundPlaces[i]; createMarker(foundPlaces[i]); addSearchResultToSide(foundPlaces[i]); places[place_id] = foundPlaces[i]; } } function callback(results, status) { if (status === google.maps.places.PlacesServiceStatus.OK) { const listOfPlacesForCache = []; const resultsLength = results.length; for (let i = 0; i < resultsLength; i++) { const { place_id } = results[i]; createMarker(results[i]); addSearchResultToSide(results[i]); places[place_id] = results[i]; listOfPlacesForCache.push(results[i]); } cachedPlaces[querySearch] = listOfPlacesForCache; } } function addSearchResultToSide(place) { const { formatted_address, place_id, name } = place; address = formatted_address.split(','); $(".results-list").append( `
${name}
${address[0]}
${address[1]}, ${address[2]}
${address[0]}
${address[1]}, ${address[2]}