Google Places API – practice

Tutorials

Do you use google maps? I am sure that yes. Have you ever tried ‘Search nearby’ function here? I like this feature and today I will show you how you can develop similar script. We will use ordinary google maps plus extra library – Places (in order to use Google Places API). Our script will be able to search for address, objects, and also you can refine your search with extra params like: keyword, type and radius.

Here you can try live demonstration, and download the sources.

Live Demo

[sociallocker]

download in package

[/sociallocker]


Ok, download the example files and lets start coding togetger!


Step 1. HTML Markup

Please create new empty html file, put basic headers and then put next code in the header section:

1 <script type="text/javascript" src="https://www.google.com/jsapi"></script>
2 <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
3 <script src="js/script.js"></script>

We have linked necessary libraries (main google library with extra library – Places) and our main script.js file (where we will put all necessary custom javascript code). Now, please put next code into body section:

index.html

01 <div id="gmap_canvas"></div>
02 <div class="actions">
03     <div class="button">
04         <label for="gmap_where">Where:</label>
05         <input id="gmap_where" type="text" name="gmap_where" /></div>
06     <div id="button2" class="button" onclick="findAddress(); return false;">Search for address</div>
07     <div class="button">
08         <label for="gmap_keyword">Keyword (optional):</label>
09         <input id="gmap_keyword" type="text" name="gmap_keyword" /></div>
10     <div class="button">
11         <label for="gmap_type">Type:</label>
12         <select id="gmap_type">
13             <option value="art_gallery">art_gallery</option>
14             <option value="atm">atm</option>
15             <option value="bank">bank</option>
16             <option value="bar">bar</option>
17             <option value="cafe">cafe</option>
18             <option value="food">food</option>
19             <option value="hospital">hospital</option>
20             <option value="police">police</option>
21             <option value="store">store</option>
22         </select>
23     </div>
24     <div class="button">
25         <label for="gmap_radius">Radius:</label>
26         <select id="gmap_radius">
27             <option value="500">500</option>
28             <option value="1000">1000</option>
29             <option value="1500">1500</option>
30             <option value="5000">5000</option>
31         </select>
32     </div>
33     <input type="hidden" id="lat" name="lat" value="40.7143528" />
34     <input type="hidden" id="lng" name="lng" value="-74.0059731" />
35     <div id="button1" class="button" onclick="findPlaces(); return false;">Search for objects</div>
36 </div>

First element (gmap_canvas) is main google map canavas object. And then – simple HTML form (of our custom filter).

Step 2. CSS

I think that now we can prepare nice styles for our demonstration page:

01 #gmap_canvas {
02     height700px;
03     positionrelative;
04     width900px;
05 }
06 .actions {
07     background-color#FFFFFF;
08     bottom30px;
09     padding10px;
10     positionabsolute;
11     right30px;
12     z-index2;
13     border-top1px solid #abbbcc;
14     border-left1px solid #a7b6c7;
15     border-bottom1px solid #a1afbf;
16     border-right1px solid #a7b6c7;
17     -webkit-border-radius: 12px;
18     -moz-border-radius: 12px;
19     border-radius: 12px;
20 }
21 .actions label {
22     displayblock;
23     margin2px 0 5px 10px;
24     text-alignleft;
25 }
26 .actions input, .actions select {
27     width85%;
28 }
29 .button {
30     background-color#d7e5f5;
31     background-image: -webkit-gradient(linear, left topleft bottom, color-stop(0%#d7e5f5), color-stop(100%#cbe0f5));
32     background-image: -webkit-linear-gradient(top#d7e5f5#cbe0f5);
33     background-image: -moz-linear-gradient(top#d7e5f5#cbe0f5);
34     background-image: -ms-linear-gradient(top#d7e5f5#cbe0f5);
35     background-image: -o-linear-gradient(top#d7e5f5#cbe0f5);
36     background-image: linear-gradient(top#d7e5f5#cbe0f5);
37     border-top1px solid #abbbcc;
38     border-left1px solid #a7b6c7;
39     border-bottom1px solid #a1afbf;
40     border-right1px solid #a7b6c7;
41     -webkit-border-radius: 12px;
42     -moz-border-radius: 12px;
43     border-radius: 12px;
44     -webkit-box-shadow: inset 0 1px 0 0 white;
45     -moz-box-shadow: inset 0 1px 0 0 white;
46     box-shadow: inset 0 1px 0 0 white;
47     color#1a3e66;
48     fontnormal 11px "Lucida Grande""Lucida Sans Unicode""Lucida Sans", Geneva, Verdanasans-serif;
49     line-height1;
50     margin-bottom5px;
51     padding6px 0 7px 0;
52     text-aligncenter;
53     text-shadow0 1px 1px #fff;
54     width150px;
55 }
56 .button:hover {
57     background-color#ccd9e8;
58     background-image: -webkit-gradient(linear, left topleft bottom, color-stop(0%#ccd9e8), color-stop(100%#c1d4e8));
59     background-image: -webkit-linear-gradient(top#ccd9e8#c1d4e8);
60     background-image: -moz-linear-gradient(top#ccd9e8#c1d4e8);
61     background-image: -ms-linear-gradient(top#ccd9e8#c1d4e8);
62     background-image: -o-linear-gradient(top#ccd9e8#c1d4e8);
63     background-image: linear-gradient(top#ccd9e8#c1d4e8);
64     border-top1px solid #a1afbf;
65     border-left1px solid #9caaba;
66     border-bottom1px solid #96a3b3;
67     border-right1px solid #9caaba;
68     -webkit-box-shadow: inset 0 1px 0 0 #f2f2f2;
69     -moz-box-shadow: inset 0 1px 0 0 #f2f2f2;
70     box-shadow: inset 0 1px 0 0 #f2f2f2;
71     color#163659;
72     cursorpointer;
73 }
74 .button:active {
75     border1px solid #8c98a7;
76     -webkit-box-shadow: inset 0 0 4px 2px #abbccf0 0 1px 0 #eeeeee;
77     -moz-box-shadow: inset 0 0 4px 2px #abbccf0 0 1px 0 #eeeeee;
78     box-shadow: inset 0 0 4px 2px #abbccf0 0 1px 0 #eeeeee;
79 }

Step 3. JS

Now, it’s time to create an empty file ‘js/script.js’ and put the next code inside:

001 var geocoder;
002 var map;
003 var markers = Array();
004 var infos = Array();
005 function initialize() {
006     // prepare Geocoder
007     geocoder = new google.maps.Geocoder();
008     // set initial position (New York)
009     var myLatlng = new google.maps.LatLng(40.7143528,-74.0059731);
010     var myOptions = { // default map options
011         zoom: 14,
012         center: myLatlng,
013         mapTypeId: google.maps.MapTypeId.ROADMAP
014     };
015     map = new google.maps.Map(document.getElementById('gmap_canvas'), myOptions);
016 }
017 // clear overlays function
018 function clearOverlays() {
019     if (markers) {
020         for (i in markers) {
021             markers[i].setMap(null);
022         }
023         markers = [];
024         infos = [];
025     }
026 }
027 // clear infos function
028 function clearInfos() {
029     if (infos) {
030         for (i in infos) {
031             if (infos[i].getMap()) {
032                 infos[i].close();
033             }
034         }
035     }
036 }
037 // find address function
038 function findAddress() {
039     var address = document.getElementById("gmap_where").value;
040     // script uses our 'geocoder' in order to find location by address name
041     geocoder.geocode( { 'address': address}, function(results, status) {
042         if (status == google.maps.GeocoderStatus.OK) { // and, if everything is ok
043             // we will center map
044             var addrLocation = results[0].geometry.location;
045             map.setCenter(addrLocation);
046             // store current coordinates into hidden variables
047             document.getElementById('lat').value = results[0].geometry.location.lat();
048             document.getElementById('lng').value = results[0].geometry.location.lng();
049             // and then - add new custom marker
050             var addrMarker = new google.maps.Marker({
051                 position: addrLocation,
052                 map: map,
053                 title: results[0].formatted_address,
054                 icon: 'marker.png'
055             });
056         else {
057             alert('Geocode was not successful for the following reason: ' + status);
058         }
059     });
060 }
061 // find custom places function
062 function findPlaces() {
063     // prepare variables (filter)
064     var type = document.getElementById('gmap_type').value;
065     var radius = document.getElementById('gmap_radius').value;
066     var keyword = document.getElementById('gmap_keyword').value;
067     var lat = document.getElementById('lat').value;
068     var lng = document.getElementById('lng').value;
069     var cur_location = new google.maps.LatLng(lat, lng);
070     // prepare request to Places
071     var request = {
072         location: cur_location,
073         radius: radius,
074         types: [type]
075     };
076     if (keyword) {
077         request.keyword = [keyword];
078     }
079     // send request
080     service = new google.maps.places.PlacesService(map);
081     service.search(request, createMarkers);
082 }
083 // create markers (from 'findPlaces' function)
084 function createMarkers(results, status) {
085     if (status == google.maps.places.PlacesServiceStatus.OK) {
086         // if we have found something - clear map (overlays)
087         clearOverlays();
088         // and create new markers by search result
089         for (var i = 0; i < results.length; i++) {
090             createMarker(results[i]);
091         }
092     else if (status == google.maps.places.PlacesServiceStatus.ZERO_RESULTS) {
093         alert('Sorry, nothing is found');
094     }
095 }
096 // creare single marker function
097 function createMarker(obj) {
098     // prepare new Marker object
099     var mark = new google.maps.Marker({
100         position: obj.geometry.location,
101         map: map,
102         title: obj.name
103     });
104     markers.push(mark);
105     // prepare info window
106     var infowindow = new google.maps.InfoWindow({
107         content: '<img src="' + obj.icon + '" /><font style="color:#000;">' + obj.name +
108         '<br />Rating: ' + obj.rating + '<br />Vicinity: ' + obj.vicinity + '</font>'
109     });
110     // add event handler to current marker
111     google.maps.event.addListener(mark, 'click'function() {
112         clearInfos();
113         infowindow.open(map,mark);
114     });
115     infos.push(infowindow);
116 }
117 // initialization
118 google.maps.event.addDomListener(window, 'load', initialize);

Let me comment this code a bit. During initialization, we prepare empty Geocoder object, then we set initial position to NewYork city, and finally we initialize Map object with our params. In the moment when we click ‘Search for address’ button, our script uses our geocoder to locate necessary address at the map. If we get some results – we take first result and put it as Marker at the map. Now, we can start searching for local objects with using of Places API. Please pay attention to ‘findPlaces’ function. As first, the script collects all selected params (type, radius, optional keyword), then it prepares request object, and sends it to PlacesService. As callback, I set ‘createMarkers’ function, this function will draw search result objects as Markers at our map. Everything is easy and logical, isn’t it?


Live Demo

Conclusion

I beleive that the ‘google maps’ have a very great future. I hope that you like our tutorials. Welcome back!

Rate article