Welcome folks today in this blog post we will be using the google places api
to find nearby places
information and display it inside the table. We will be using the given
location from the autocomplete
location field in browser using javascript.
LIVE DEMO
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 |
<!DOCTYPE html> <html> <head> <title>Google Places API Example</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css"> </head> <body> <div class="container"> <br><br> <h1 class="text-center">Nearby Places Finder</h1> <div id="map"></div> <div class="form-group"> <label for="location">Enter Location: (Autocomplete)</label> <br> <input class="form-control" id="autocomplete" type="text" placeholder="Enter a location"> </div> <br> <div class="form-group"> <label for="type">Select Place Type:</label> <br> <select class="form-control" name="" id="type"> <option id='accounting'>accounting</option> <option id='airport'>airport</option> <option id='amusement_park'>amusement_park</option> <option id='aquarium'>aquarium</option> <option id='art_gallery'>art_gallery</option> <option id='atm'>atm</option> <option id='bakery'>bakery</option> <option id='bank'>bank</option> <option id='bar'>bar</option> <option id='beauty_salon'>beauty_salon</option> <option id='bicycle_store'>bicycle_store</option> <option id='book_store'>book_store</option> <option id='bowling_alley'>bowling_alley</option> <option id='bus_station'>bus_station</option> <option id='cafe'>cafe</option> <option id='campground'>campground</option> <option id='car_dealer'>car_dealer</option> <option id='car_rental'>car_rental</option> <option id='car_repair'>car_repair</option> <option id='car_wash'>car_wash</option> <option id='casino'>casino</option> <option id='cemetery'>cemetery</option> <option id='church'>church</option> <option id='city_hall'>city_hall</option> <option id='clothing_store'>clothing_store</option> <option id='convenience_store'>convenience_store</option> <option id='courthouse'>courthouse</option> <option id='dentist'>dentist</option> <option id='department_store'>department_store</option> <option id='doctor'>doctor</option> <option id='drugstore'>drugstore</option> <option id='electrician'>electrician</option> <option id='electronics_store'>electronics_store</option> <option id='embassy'>embassy</option> <option id='fire_station'>fire_station</option> <option id='florist'>florist</option> <option id='funeral_home'>funeral_home</option> <option id='furniture_store'>furniture_store</option> <option id='gas_station'>gas_station</option> <option id='gym'>gym</option> <option id='hair_care'>hair_care</option> <option id='hardware_store'>hardware_store</option> <option id='hindu_temple'>hindu_temple</option> <option id='home_goods_store'>home_goods_store</option> <option id='hospital'>hospital</option> <option id='insurance_agency'>insurance_agency</option> <option id='jewelry_store'>jewelry_store</option> <option id='lawyer'>lawyer</option> <option id='library'>library</option> <option id='light_rail_station'>light_rail_station</option> <option id='liquor_store'>liquor_store</option> <option id='local_government_office'>local_government_office</option> <option id='locksmith'>locksmith</option> <option id='lodging'>lodging</option> <option id='meal_delivery'>meal_delivery</option> <option id='meal_takeaway'>meal_takeaway</option> <option id='mosque'>mosque</option> <option id='movie_rental'>movie_rental</option> <option id='movie_theater'>movie_theater</option> <option id='moving_company'>moving_company</option> <option id='museum'>museum</option> <option id='night_club'>night_club</option> <option id='painter'>painter</option> <option id='park'>park</option> <option id='parking'>parking</option> <option id='pet_store'>pet_store</option> <option id='pharmacy'>pharmacy</option> <option id='physiotherapist'>physiotherapist</option> <option id='plumber'>plumber</option> <option id='police'>police</option> <option id='post_office'>post_office</option> <option id='primary_school'>primary_school</option> <option id='real_estate_agency'>real_estate_agency</option> <option id='restaurant'>restaurant</option> <option id='roofing_contractor'>roofing_contractor</option> <option id='rv_park'>rv_park</option> <option id='school' selected>school</option> <option id='secondary_school'>secondary_school</option> <option id='shoe_store'>shoe_store</option> <option id='shopping_mall'>shopping_mall</option> <option id='spa'>spa</option> <option id='stadium'>stadium</option> <option id='storage'>storage</option> <option id='store'>store</option> <option id='subway_station'>subway_station</option> <option id='supermarket'>supermarket</option> <option id='synagogue'>synagogue</option> <option id='taxi_stand'>taxi_stand</option> <option id='tourist_attraction'>tourist_attraction</option> <option id='train_station'>train_station</option> <option id='transit_station'>transit_station</option> <option id='travel_agency'>travel_agency</option> <option id='university'>university</option> <option id='veterinary_care'>veterinary_care</option> </select> </div> <br><br> <table class="table table-bordered table-striped" id="places"></table> </div> </body> <script src="https://maps.googleapis.com/maps/api/js?key=##yourapikey##&libraries=places&callback=initMap" async defer></script> </html> |
As you can see we have the above html
for the web app in which we have the address
autocomplete field where we allow the user to enter the pinpoint location using the google geocode
api and then we have the select
field where we have different options to select place types. And then we have the table
where we show the information of the places such as the name
and the picture
of the place. And also at the bottom we are including the script
tag of the google places api
and here you need to copy paste your own api_key
from google cloud console and also you need to enable the apis as shown below
And also as you can see we are executing the initMap()
method inside the callback
parameter. So when the library is loaded
this function will automatically execute. So now we need to write the javascript
code and define this function as shown below
1 2 3 4 5 6 7 8 9 |
function initMap() { autocomplete = new google.maps.places.Autocomplete( document.getElementById("autocomplete"), { types: ["geocode"] } ); // When the user selects an address from the dropdown, search for nearby places. autocomplete.addListener("place_changed", searchNearbyPlaces); } |
As you can see in the above function we are fetching all the autocomplete
location suggestions from the geocode
api of google and then inserting them to the autocomplete
field using it’s id. And then we are binding a listener to the input field such that whenever the location
is changed by the user then searchNearbyPlaces()
method will execute everytime as shown below
1 |
ocument.getElementById('type').onchange = searchNearbyPlaces |
And also when the value of the place type
select field changes then also we need to execute the same searchNearbyPlaces()
method so we binded a onchange
event listener as shown above.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
function searchNearbyPlaces() { document.getElementById("places").innerHTML = ""; // Get the place details from the autocomplete object. var place = autocomplete.getPlace(); console.log(place); // Create a map centered at the location entered in the autocomplete field. map = new google.maps.Map(document.getElementById("map"), { center: place.geometry.location, zoom: 15, }); // Perform a nearby search for places of type 'store'. service = new google.maps.places.PlacesService(map); service.nearbySearch( { location: place.geometry.location, radius: "500", type: [document.getElementById("type").value], }, callback ); } |
As you can see we are getting the location
selected by the user and then we are calling the places api
to get details about the location and here we are passing the location
and then we are also passing the radius
value to be 500 and then we are passing the place type
and then if this request is successful then callback
function will execute automatically.
1 2 3 4 5 6 7 8 |
function callback(results, status) { if (status === google.maps.places.PlacesServiceStatus.OK) { console.log(results.length) for (var i = 0; i < results.length; i++) { createMarker(results[i]); } } } |
As you can see inside the above callback
function we are getting the no
of places returned and then we are using the simple for
loop to iterate over each place and insert it or display it inside the table
fetching the name and the picture of the place and for this we are calling the createMarker()
method and passing the actual result
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function createMarker(place) { console.log(place) var table = document.getElementById("places"); var row = table.insertRow(); var cell1 = row.insertCell(0); cell1.innerHTML = place.name; if (place.photos) { let photoUrl = place.photos[0].getUrl(); let cell2 = row.insertCell(1) cell2.innerHTML = `<img width="300" height="300" src="${photoUrl}"/>` } else { let photoUrl = "https://via.placeholder.com/150" let cell2 = row.insertCell(1) cell2.innerHTML = `<img width="300" height="300" src="${photoUrl}"/>` } } |
As you can see we are getting the place
object and from that we are getting the name
and photos
properties and then we are creating the table
element and inside it we are displaying these two things such as the name and the picture
of the place. If the picture is not present for any place then we are showing the placeholder
image.
FULL SOURCE CODE
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
<!DOCTYPE html> <html> <head> <title>Google Places API Example</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css"> </head> <body> <div class="container"> <br><br> <h1 class="text-center">Nearby Places Finder</h1> <div id="map"></div> <div class="form-group"> <label for="location">Enter Location: (Autocomplete)</label> <br> <input class="form-control" id="autocomplete" type="text" placeholder="Enter a location"> </div> <br> <div class="form-group"> <label for="type">Select Place Type:</label> <br> <select class="form-control" name="" id="type"> <option id='accounting'>accounting</option> <option id='airport'>airport</option> <option id='amusement_park'>amusement_park</option> <option id='aquarium'>aquarium</option> <option id='art_gallery'>art_gallery</option> <option id='atm'>atm</option> <option id='bakery'>bakery</option> <option id='bank'>bank</option> <option id='bar'>bar</option> <option id='beauty_salon'>beauty_salon</option> <option id='bicycle_store'>bicycle_store</option> <option id='book_store'>book_store</option> <option id='bowling_alley'>bowling_alley</option> <option id='bus_station'>bus_station</option> <option id='cafe'>cafe</option> <option id='campground'>campground</option> <option id='car_dealer'>car_dealer</option> <option id='car_rental'>car_rental</option> <option id='car_repair'>car_repair</option> <option id='car_wash'>car_wash</option> <option id='casino'>casino</option> <option id='cemetery'>cemetery</option> <option id='church'>church</option> <option id='city_hall'>city_hall</option> <option id='clothing_store'>clothing_store</option> <option id='convenience_store'>convenience_store</option> <option id='courthouse'>courthouse</option> <option id='dentist'>dentist</option> <option id='department_store'>department_store</option> <option id='doctor'>doctor</option> <option id='drugstore'>drugstore</option> <option id='electrician'>electrician</option> <option id='electronics_store'>electronics_store</option> <option id='embassy'>embassy</option> <option id='fire_station'>fire_station</option> <option id='florist'>florist</option> <option id='funeral_home'>funeral_home</option> <option id='furniture_store'>furniture_store</option> <option id='gas_station'>gas_station</option> <option id='gym'>gym</option> <option id='hair_care'>hair_care</option> <option id='hardware_store'>hardware_store</option> <option id='hindu_temple'>hindu_temple</option> <option id='home_goods_store'>home_goods_store</option> <option id='hospital'>hospital</option> <option id='insurance_agency'>insurance_agency</option> <option id='jewelry_store'>jewelry_store</option> <option id='lawyer'>lawyer</option> <option id='library'>library</option> <option id='light_rail_station'>light_rail_station</option> <option id='liquor_store'>liquor_store</option> <option id='local_government_office'>local_government_office</option> <option id='locksmith'>locksmith</option> <option id='lodging'>lodging</option> <option id='meal_delivery'>meal_delivery</option> <option id='meal_takeaway'>meal_takeaway</option> <option id='mosque'>mosque</option> <option id='movie_rental'>movie_rental</option> <option id='movie_theater'>movie_theater</option> <option id='moving_company'>moving_company</option> <option id='museum'>museum</option> <option id='night_club'>night_club</option> <option id='painter'>painter</option> <option id='park'>park</option> <option id='parking'>parking</option> <option id='pet_store'>pet_store</option> <option id='pharmacy'>pharmacy</option> <option id='physiotherapist'>physiotherapist</option> <option id='plumber'>plumber</option> <option id='police'>police</option> <option id='post_office'>post_office</option> <option id='primary_school'>primary_school</option> <option id='real_estate_agency'>real_estate_agency</option> <option id='restaurant'>restaurant</option> <option id='roofing_contractor'>roofing_contractor</option> <option id='rv_park'>rv_park</option> <option id='school' selected>school</option> <option id='secondary_school'>secondary_school</option> <option id='shoe_store'>shoe_store</option> <option id='shopping_mall'>shopping_mall</option> <option id='spa'>spa</option> <option id='stadium'>stadium</option> <option id='storage'>storage</option> <option id='store'>store</option> <option id='subway_station'>subway_station</option> <option id='supermarket'>supermarket</option> <option id='synagogue'>synagogue</option> <option id='taxi_stand'>taxi_stand</option> <option id='tourist_attraction'>tourist_attraction</option> <option id='train_station'>train_station</option> <option id='transit_station'>transit_station</option> <option id='travel_agency'>travel_agency</option> <option id='university'>university</option> <option id='veterinary_care'>veterinary_care</option> </select> </div> <br><br> <table class="table table-bordered table-striped" id="places"></table> </div> <script> function initMap() { autocomplete = new google.maps.places.Autocomplete((document.getElementById('autocomplete')), { types: ['geocode'] }); // When the user selects an address from the dropdown, search for nearby places. autocomplete.addListener('place_changed', searchNearbyPlaces); } document.getElementById('type').onchange = searchNearbyPlaces function searchNearbyPlaces() { document.getElementById('places').innerHTML = '' // Get the place details from the autocomplete object. var place = autocomplete.getPlace(); console.log(place) // Create a map centered at the location entered in the autocomplete field. map = new google.maps.Map(document.getElementById('map'), { center: place.geometry.location, zoom: 15 }); // Perform a nearby search for places of type 'store'. service = new google.maps.places.PlacesService(map); service.nearbySearch({ location: place.geometry.location, radius: '500', type: [document.getElementById('type').value] }, callback); } function callback(results, status) { if (status === google.maps.places.PlacesServiceStatus.OK) { console.log(results.length) for (var i = 0; i < results.length; i++) { createMarker(results[i]); } } } function createMarker(place) { console.log(place) var table = document.getElementById("places"); var row = table.insertRow(); var cell1 = row.insertCell(0); cell1.innerHTML = place.name; if (place.photos) { let photoUrl = place.photos[0].getUrl(); let cell2 = row.insertCell(1) cell2.innerHTML = `<img width="300" height="300" src="${photoUrl}"/>` } else { let photoUrl = "https://via.placeholder.com/150" let cell2 = row.insertCell(1) cell2.innerHTML = `<img width="300" height="300" src="${photoUrl}"/>` } } </script> <script src="https://maps.googleapis.com/maps/api/js?key=##yourapikey##&libraries=places&callback=initMap" async defer></script> </body> </html> |