× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Setting up an open-source "suggest location" search

<p>Have you ever wanted to ask for users' locations, in order to provide them with place-specific content? This can be great for surveys, product funneling, sales, mapping geospatial data, and tons more things. I've used it myself on http://native-land.ca and a host of other sites, in a lot of situations.<br> <br> Google provides a good autocomplete tutorial <a href="https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete">on their website</a>, but this can be a bit intimidating if you just want the autocomplete by itself, without maps and stuff. Here's a little walkthrough on getting up and running.<br> <br> <strong>1. Set up the Google Maps script.</strong></p> <p>Google no longer requires an API key to use basic maps, which is great. There is a limit for geocoding (which is what we're doing with an autocomplete), so if you are planning to use this on a big scale, check Google's pricing.<br> <br> In your HTML, near the footer, add:</p> <pre><code class="language-javascript">&lt;script src="https://maps.googleapis.com/maps/api/js?libraries=places"&gt;&lt;/script&gt;</code></pre> <p>This gets the Places library, which we need for autocomplete.</p> <p><strong>2. Add your search input HTML</strong></p> <p>Head up to where you want your search input to appear, and add:</p> <pre><code class="language-html">&lt;input id="cm-autocomplete" class="controls" type="text" placeholder="Enter your location!" /&gt;</code></pre> <p><br> 3. Under your call to the Google Maps script, add the Input trigger and call to the Places API.</p> <pre><code class="language-javascript">&lt;script&gt; // Register input var input = document.getElementById('cm-autocomplete'); var autocomplete = new google.maps.places.Autocomplete(input); // Call to API if input changes autocomplete.addListener('place_changed', function() { var place = autocomplete.getPlace(); if (!place.geometry) { window.alert("Autocomplete's returned place contains no geometry"); return; } console.log(place); }); &lt;/script&gt;</code></pre> <p>Your autocomplete should now be up and running! If it didn't work for you, see the example on <a href="https://jsbin.com/reruvagiba/edit?html,console,output">JSBin here</a>.<br> <br> The "place" object logged in the example above contains all kinds of information about the place name, coordinates, districts, and much more. Enjoy!</p>
comments powered by Disqus