Google Maps- Find Places, Restaurants Etc. With Animated Marker Using Bootstrap In ASP.NET MVC

Introduction

Google Maps API allows you to display maps on your ASP.NET MVC Website.

Description

An API is a set of methods and tools which can be used for building software applications.

The SearchBox allows users to perform a text-based geographic search. You can attach the SearchBox to a text field and, as text is entered, the service will return predictions in the form of a drop-down pick list.

SearchBox supplies an extended list of predictions, which can include places as defined by the Google Places API plus suggested search terms. When a user selects a place from the list, information about that place is returned to the SearchBox object, and can be retrieved by your application.

The SearchBox constructor takes two arguments

An HTML input element of type text. This is the input field that the SearchBox service will monitor and attach its results to. An options argument, which can contain the bounds property: bounds is a google.maps.LatLngBounds object specifying the area in which to search for places.

The results are biased towards, but not restricted to, places contained within these bounds.The following code uses the bounds parameter to bias the results towards places within a particular geographic area, specified via laitude/longitude coordinates.

Get SearchBox information

When the user selects an item from the predictions attached to the search box, the service fires a places_changed event. You can call getPlaces() on the SearchBox object, to retrieve an array containing several predictions, each of which is a PlaceResult object.

Autocomplete is a feature of the Places library in the Google Maps JavaScript API. You can use autocomplete to give your applications the type-ahead-search behavior of the Google Maps search field. When a user starts typing an address, autocomplete will fill in the rest.

As defined by the Google Places API, a 'place' can be an establishment, a geographic location, or a prominent point of interest.
 
Loading the library

The Places service is a self-contained library, separate from the main Maps JavaScript API code. To use the functionality contained within this library, you must first load it using the libraries parameter in the Maps API bootstrap URL,
  1. <script async defer src="https://maps.googleapis.com/maps/api/js?key=Put_YoUR_Key&libraries=places&callback=initAutocomplete"></script>  
The API offers two types of autocomplete options, which you can add via the Autocomplete and SearchBox classes respectively.
In addition, you can use the AutocompleteService class to retrieve autocomplete results programmatically.
  1. Autocomplete adds a text input field to your web page, and monitors that field for character entries. As the user enters text,  autocomplete returns place predictions in the form of a dropdown pick list. When the user selects a place from the list,  information about the place is returned to the autocomplete object, and can be retrieved by your application.

  2. SearchBox adds a text input field to your web page, in much the same way as Autocomplete. The differences are as follows, The main difference lies in the results that appear in the pick list. SearchBox supplies an extended list of predictions, which can include places (as defined by the Google Places API) plus suggested search terms. For example, if the user enters 'pizza in new', the pick list may include the phrase 'pizza in New York, NY' as well as the names of various pizza outlets. SearchBox offers fewer options than Autocomplete for restricting the search. In the former, you can bias the search towards a given LatLngBounds.

    In the latter, you can restrict the search to a particular country and particular place type, as well as setting the bounds.

  3. You can create an AutocompleteService object to retrieve predictions programmatically. Call getPlacePredictions() to retrieve matching places, or call getQueryPredictions() to retrieve matching places plus suggested search terms.

    Note

    AutocompleteService does not add any UI controls. Instead, the above methods return an array of prediction objects. Each prediction object contains the text of the prediction, as well as reference information and details of how the result matches the user input.

  4. When a user selects a place from the predictions attached to the autocomplete text field, the service fires a place_changed event. You can call getPlace() on the Autocomplete object, to retrieve a PlaceResult object. By default, autocomplete will give you the full address as a single line of text. For an address form, it is useful to get the address in structured format. You can use Autocomplete.getPlace() to retrieve the full details for each autocomplete prediction, including the structured address. If you use the placeIdOnly option, the Autocomplete object will not get place details, as the PlaceResult object has only the place_id, types and name properties set. To get place details, retrieve a PlaceResult object by calling getPlace() on the Autocomplete object when you get the place_changed event. 
You could then use geocoding to get the location coordinates, or the Places service to get more information on the selected place.

Reference

For more details visit my blogs related to Google Map.

http://www.c-sharpcorner.com/members/satyaprakash-samantaray/blogs/ 
 
Steps

You will need to register and get an API key from Google API, which will be used to load and display Google Map. 
 
 
Step 1

Create a MVC Application named SatyaGoogleMapBootstrapMVC. Now, create a controller class file named HomeController.cs with controller action method named "Steet()".

Code Ref
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace SatyaGoogleMapBootstrapMVC.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         //  
  12.         // GET: /Home/  
  13.   
  14.         public ActionResult Index()  
  15.         {  
  16.             return View();  
  17.         }  
  18.         public ActionResult Details()  
  19.         {  
  20.             return View();  
  21.         }  
  22.         public ActionResult Animate()  
  23.         {  
  24.             return View();  
  25.         }  
  26.         public ActionResult Icon()  
  27.         {  
  28.             return View();  
  29.         }  
  30.         public ActionResult Steet()  
  31.         {  
  32.             return View();  
  33.         }  
  34.     }  

Code Description

Here, Steet Controller action method is taken to create the view for current application.
 
 
 
Step 2

Create a View based on Controller Action Method Steet() named Steet.cshtml. 
 
Code Ref
  1. @{  
  2.     ViewBag.Title = "Satyaprakash Autocomplete Places search";  
  3. }  
  4.   
  5. <title>@ViewBag.Title</title>  
  6.   
  7. <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">Satyaprakash's Google Map Autocomplete Places Search Using MVC and BOOTSTRAP</h2>  
  8.     <meta charset="utf-8">  
  9.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  10.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
  11.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
  12.     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>  
  13.   
  14.     <title>Places Searchbox</title>  
  15.     <style>  
  16.         
  17.          #map {  
  18.              height: 60%;  
  19.          }  
  20.           
  21.          html, body {  
  22.              height: 100%;  
  23.              margin: 0;  
  24.              padding: 0;  
  25.          }  
  26.  
  27.        
  28.            
  29.          #title {  
  30.              color: red;  
  31.              background-color: yellow;  
  32.              font-size: 25px;  
  33.              font-weight: 500;  
  34.              padding: 6px 12px;  
  35.          }  
  36.   
  37.          
  38.         input[type=text], select {  
  39.             width: 60%;  
  40.             padding: 12px 20px;  
  41.             margin: 8px 0;  
  42.             display: inline-block;  
  43.             border: 1px solid #ccc;  
  44.             border-radius: 4px;  
  45.             box-sizing: border-box;  
  46.         }  
  47.     </style>  
  48.   
  49.         <input id="pac-input" type="text" placeholder="Search Place....">  
  50.         <div id="map"></div>  
  51.         <script>  
  52.              
  53.   
  54.             function initAutocomplete() {  
  55.                 var map = new google.maps.Map(document.getElementById('map'), {  
  56.                     center: { lat: 20.296100, lng: 85.824500 },  
  57.                     zoom: 13,  
  58.                     mapTypeId: 'roadmap'  
  59.                 });  
  60.   
  61.                 
  62.                 var input = document.getElementById('pac-input');  
  63.                 var searchBox = new google.maps.places.SearchBox(input);  
  64.                 map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);  
  65.   
  66.                 
  67.                 map.addListener('bounds_changed'function () {  
  68.                     searchBox.setBounds(map.getBounds());  
  69.                 });  
  70.   
  71.                 var markers = [];  
  72.                   
  73.                 searchBox.addListener('places_changed'function () {  
  74.                     var places = searchBox.getPlaces();  
  75.   
  76.                     if (places.length == 0) {  
  77.                         return;  
  78.                     }  
  79.   
  80.                    
  81.                     markers.forEach(function (marker) {  
  82.                         marker.setMap(null);  
  83.                     });  
  84.                     markers = [];  
  85.   
  86.                   
  87.                     var bounds = new google.maps.LatLngBounds();  
  88.                     places.forEach(function (place) {  
  89.                         if (!place.geometry) {  
  90.                             console.log("Returned place contains no geometry");  
  91.                             return;  
  92.                         }  
  93.                         var icon = {  
  94.                             url: place.icon,  
  95.                             size: new google.maps.Size(71, 71),  
  96.                             origin: new google.maps.Point(0, 0),  
  97.                             anchor: new google.maps.Point(17, 34),  
  98.                             scaledSize: new google.maps.Size(25, 25)  
  99.                         };  
  100.   
  101.                          
  102.                         markers.push(new google.maps.Marker({  
  103.                             map: map,  
  104.                             icon: "Flag.jpg",  
  105.                             title: place.name,  
  106.                             position: place.geometry.location,  
  107.                             animation: google.maps.Animation.BOUNCE  
  108.                         }));  
  109.   
  110.                         if (place.geometry.viewport) {  
  111.                             
  112.                             bounds.union(place.geometry.viewport);  
  113.                         } else {  
  114.                             bounds.extend(place.geometry.location);  
  115.                         }  
  116.                     });  
  117.                     map.fitBounds(bounds);  
  118.                 });  
  119.             }  
  120.   
  121.         </script>  
  122.   
  123.         <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkVZYQFe4YYva_g5ulymGDt9EBoVjjZJ8&libraries=places&callback=initAutocomplete"></script>  
  124.   
  125. <footer>  
  126.     <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  127. </footer> 
Code Description

Here I added bootstrap related references information to support bootstrap.
  1. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
  2.    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
  3.    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
I added a css style sheet for map and search textbox. Always set the map height explicitly to define the size of the div element that contains the map.
  1. #map {  
  2.              height60%;  
  3.          } 
Optional

Makes the sample page fill the window.
  1. html, body {  
  2.              height100%;  
  3.              margin0;  
  4.              padding0;  
  5.          }  
  6.  #title {  
  7.              colorred;  
  8.              background-color: yellow;  
  9.              font-size25px;  
  10.              font-weight500;  
  11.              padding6px 12px;  
  12.          } 
For Search textbox , I added it here.
  1. input[type=text], select {  
  2.             width60%;  
  3.             padding12px 20px;  
  4.             margin8px 0;  
  5.             display: inline-block;  
  6.             border1px solid #ccc;  
  7.             border-radius: 4px;  
  8.             box-sizing: border-box;  
  9.         } 
I added textbox control in Asp.net MVC.
  1. <input id="pac-input" type="text" placeholder="Search Place...."
This example adds a search box to a map, using the Google Place Autocomplete feature. People can enter geographical searches. The search box will return a pick list containing a mix of places and predicted search terms. This example requires the Places library. Include the libraries=places parameter when you first load the API. For example,
  1. <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"
 When the page will load first time the Bhubaneswar place will display, as I mentioned longitude and latitude and maptype.
  1. function initAutocomplete() {  
  2.                var map = new google.maps.Map(document.getElementById('map'), {  
  3.                    center: { lat: 20.296100, lng: 85.824500 },  
  4.                    zoom: 13,  
  5.                    mapTypeId: 'roadmap'  
  6.                }); 
 Create the search box and link it to the UI element.
  1. var input = document.getElementById('pac-input');  
  2.                 var searchBox = new google.maps.places.SearchBox(input);  
  3.                 map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); 
 Bias the SearchBox results towards current map's viewport.
  1. map.addListener('bounds_changed'function () {  
  2.                     searchBox.setBounds(map.getBounds());  
  3.                 });  
  4.   
  5.                 var markers = []; 
 Listen for the event fired when the user selects a prediction and retrieve more details for that place.
  1. searchBox.addListener('places_changed'function () {  
  2.                     var places = searchBox.getPlaces();  
  3.   
  4.                     if (places.length == 0) {  
  5.                         return;  
  6.                     } 
 Clear out the old markers.
  1. markers.forEach(function (marker) {  
  2.                         marker.setMap(null);  
  3.                     });  
  4.                     markers = []; 
 For each place, get the icon, name and location.
  1. var bounds = new google.maps.LatLngBounds();  
  2.                     places.forEach(function (place) {  
  3.                         if (!place.geometry) {  
  4.                             console.log("Returned place contains no geometry");  
  5.                             return;  
  6.                         }  
  7.                         var icon = {  
  8.                             url: place.icon,  
  9.                             size: new google.maps.Size(71, 71),  
  10.                             origin: new google.maps.Point(0, 0),  
  11.                             anchor: new google.maps.Point(17, 34),  
  12.                             scaledSize: new google.maps.Size(25, 25)  
  13.                         }; 
 Create a marker for each place . I put my own image file like '.jpg' file.
  1. markers.push(new google.maps.Marker({  
  2.                             map: map,  
  3.                             icon: "Flag.jpg",  
  4.                             title: place.name,  
  5.                             position: place.geometry.location,  
  6.                             animation: google.maps.Animation.BOUNCE  
  7.                         })); 
 
 
Only geocodes have viewport.
  1. if (place.geometry.viewport) {  
  2.                             
  3.                           bounds.union(place.geometry.viewport);  
  4.                       } else {  
  5.                           bounds.extend(place.geometry.location);  
  6.                       }  
  7.                   }); 
 Then finally the all properties are set to div map.
  1. map.fitBounds(bounds); 
 Then I put my google api key with Places library package and function name 'initAutocomplete'.
  1. <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkVZYQFe4YYva_g5ulymGDt9EBoVjjZJ8&libraries=places&callback=initAutocomplete"></script> 
 
 
OUTPUT

DESKTOP VIEW
 
In the Initial Load the Bhubaneswar location will appear as I  described earlier.

 

When you display predictions from the Google Places search box, you must include the 'powered by Google' logo. 

 

When search by Bangalore , the textbox shows City name with Country name and State Name.

 
 
Now, the search city with animated marker is found.

 

Now, I will search using KFC Restaurant store in Bangalore City..

 

Now, I search with "accenture near ECO Space " in Bangalore City..

 
 
Mobile View

In mobile view, the text box and map control are adjusted automatically based on the screen size.
 
 
 
 
Desktop View
 
When I search By HSR LAYOUT, Bangalore

 

When I search some KFC Restaurant store new HSR Layout, Bangalore.
 

 
Mobile View

 
 
 
 
Like this, you can search anything - an IT company, MBA colleges, banks etc. 

SUMMARY

Here, we learned the following.
  1. What is Google Map Find Places.
  2. How to implement it in Asp.net MVC.
  3. To know more details  go through my blog related to Google maps using Bootstrap In Asp.Net MVC.
  4. How to get google api key and places library package.


Similar Articles