Autocomplete input for addresses (GMap API)
First of all, I would like to say this will be my first article in English. If I sucked writing articles in my mother tongue, imagine how this will end up. Saying that...
I don't consider myself a good developer, and if we consider front-end development I think I'm even worst.
This is my learning about creating an autocomplete input with addresses using the Google Map API. To be honest, it is a very simple example, but I had to take care of some things to avoid extra charges.
The main goal was creating a simple component where the user could type an address (for a particular country) and that should be converted to coordinates. It sounds pretty simple, right? Well, it is.
The Google documentation is quite complete and has tons of examples, but sometimes could be too overwhelmed. In my case, I had to remove more code from the example than add new lines.
But as Linus Torvalds said, 'Talk is cheap. Show me the code.'
HTML
With an input and script tag should be enough, of course, if you want to do it beautiful you would need more code.
<input id="autocomplete" placeholder="Enter your address" type="text" class="form-control">
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete" async defer></script>
In the official documentation, you will see this code portion inside of a complex one. And if you compare both in detail, you will see the input have an additional property (onfocus
). This is because they create a function to set a bias into the search using the geolocation of the user.
As I mentioned before, I don't need that feature since I'm going to restrict the search to only one country. So, wherever you are, the addresses result will be always the same, it's like a fixed bias (Does the term even exist?).
Note the script tag, there you should include your API key (I’ll explain below how to create and configure it to be as cheaper as possible).
Javascript
Here is almost copy and paste (like always in our jobs, isn’t it?). I only did some modifications to the Documentation example to fit better to my needs.
let placeSearch, autocomplete;
let countryRestriction = {'country': 'ar'};
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** @type {!HTMLInputElement} */
document.getElementById('autocomplete'),
{
types: ['geocode'],
componentRestrictions: countryRestriction
}
);
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
}
function fillInAddress() {
// Get the place details from the autocomplete object.
autocomplete.setFields(["geometry"]);
var location = autocomplete.getPlace().geometry.location;
document.getElementById("lat").value = location.lat();
document.getElementById("long").value = location.lng();
}
Some things to keep in mind:
- I'm declaring a variable
countryRestriction
that will contain the country code to filter the search criteria only to (in this case) Argentina. - It's important to use the
setFields
method to specify which information we want to receive from the API. Why is so important? If you don't set anything, the response would contain all the information available and you are going to be charged for that. So, it's better less than more.
As you can see above, I'm only requesting the geometry
object, this is because I only need latitude and longitude. In case you need further information (like address name, zip code, state, city, etc) you would need to set in the setFields
method.
Get an API Key
To do so, you would need to access the Google Console Platform and create a new project. Once you do that, go to the menu button >> APIs & Services >> Credentials, you will see a button "+ CREATE CREDENTIALS" and under the options choose "API KEY".
Later, you will need to enable two APIs: Places API
and Maps Javascript API
. How can you do that? Well, it's quite simple, if you go to the menu button >> APIs & Services and then click on the button "+ ENABLE APIS AND SERVICES" you will have to search for those APIs and enable them.
Finally, you need to associate your API KEY with those two APIs, for that, just go to edit your recently created credential and under the section API restrictions select them from the list.
Suggestions
Since the Places API is free but the Maps Javascript API isn't, I would suggest doing additional setup to avoid extra charges.
- Try to select the more restrictive Application restrictions. To ensure that only you are calling the API with your key.
- Do the same for Website restrictions, here you can add more than one URL, even you can add your local instance.