Address field with autocomplete – step by step tutorial with JSFiddle example

Adding an address field ideally with autocomplete is a very common task for web-developer. And even if there are libraries providing components and “ready-to-use” solutions they often are difficult to style, missing some functionality required and need to be maintained. Moreover, when you start to use a component “from-a-box” you bind yourself with the exact API provider.

In this tutorial, we propose you to create an address field with autocomplete with Vanilla Javascript only. We use the Geoapify Geocoding service to convert addresses into locations and JSFiddle for a playground.

Before you start

Register and get an API key for free on MyProjects Geoapify. We have a Freemium pricing model, so you can start for Free and extend when you need it.

We provide an API key for JSFiddle example and you can reuse it for other JSFiddle examples. However, you require your own API key to make API calls from your own application.

Step 1. Create an input field in a provided HTML-container

  • We start just with a DIV-element, which is positioned relatively;
  • Let’s create an input field inside the container and make it spread full width:

Step 2. Send a geocoding request on user input and show a dropdown list with results

  • Now let’s add a user input event and send a geocoding request when the event is fired;
  • As the geocoding result comes asynchronously we need to cancel the previous request if the user input changes;
  • We create a DIV-element with geocoding results and show it as a dropdown to the input element;
  • We hide the dropdown list on new user input:

Step 3. Select an option and notify when an option was selected

  • Now let’s make options clickable and notify about selected option;
  • We add a callback parameter to the addressAutocomplete() to get notifications:

Geoapify Geocoding API returns results in GeoJSON format. Learn more about GeoJSON feature properties on the Geocoding documentation page.

Step 4. Add clear button

The Geocoding Autocomplete is functional now, but not user-friendly enough. Let’s improve this!

  • Add a clear button to the input field;
  • Hide the button when input is empty;
  • Send notification when the text was cleared:

Step 5. Add keyboard navigation support

It would be great to have the possibility to navigate the address field with a keyboard.

  • Let’s add a listener for arrow UP, arrow DOWN and ENTER key;
  • We are going to navigate and send notifications when a user navigates the dropdown list;
  • The focused item in the dropdown list is highlighted with a background color. We store the index of the focused element in the focusedItemIndex;
  • We close the dropdown list when the user presses ENTER:

Step 6. Make the dropdown list responsive

At the moment the dropdown is opened when a user types in the input field and closed only when an option was selected. Let’s close the dropdown list when a user clicked outside the input control and show the dropdown list again when the control is clicked again:

Step 7. Search countries, cities, streets

Geoapify Geocoding API allows specifying a type for locations. Let’s add a parameter for the addressAutocomplete() that limits the search to the specific location type:

Geoapify Geocoding API parameters

With Goeapify Geocoding you can make your search more concrete:

  • Search by exact address type. For example, search only countries, cities or streets.
  • Limit the search to a list of counties.
  • Search around a given location.
  • Change the language of results.

Learn more about Geoapify Geocoding API parameters and options.

Angular + Leaflet: step by step tutorial to add a map

This tutorial helps you to create an Angular-based application and add a Leaflet map as a component. In our tutorial, we provide a way to use the Leaflet library without additional components. Moreover, we prepared an Angular-project for you that contains already a component skeleton for the map component.

We use Geoapify map tiles for the tutorial. You can choose between different map styles and colors there. Check the Geoapify Maps Playground that contains Live demo and code samples.

We use Mapbox style specification, which describes how the map is rendered, tile server locations, and provides values for map settings. For example, minimum, and maximal zoom levels.

Before you start

Step 1. Create an Angular project

You can use the Angular project template we’ve prepared for you or create a new one with Angular CLI. The project template contains already a component for a map:

  • Download or clone the GitHub repository
  • Switch to the project folder: cd angular-based-project
  • Run npm install to install libraries and dependencies
  • Run ng serve for a dev server
  • Navigate to http://localhost:4200/. The app will automatically reload if you change any of the source files.

Step 2. Display a map with Leaflet

Install Leaflet + Mapbox GL plugin

By default, Leaflet doesn’t support vector tiles and Mapbox Style specifications. Therefore you need to install the Mapbox GL Leaflet plugin together with Leaflet to generate a map from style.json:

npm i leaflet mapbox-gl mapbox-gl-leaflet
Install Leaflet + Mapbox GL types

Type definitions will allow you to utilize Leaflet and Mapbox types in your code. Moreover, some IDEs provide code completion when the types are available:

npm i @types/leaflet @types/mapbox-gl-leaflet -dev
Add Leaflet and Mapbox styles

Leaflet and Mapbox styles are required to render a map and it’s elements correctly. We recommend you to add styles to the angular.json:

"projects": {
    "angular-project": {
      ...
      "architect": {
        "build": {
          "options": {
            ...
            "styles": [
              "src/styles.scss",
              "node_modules/mapbox-gl/dist/mapbox-gl.css",
              "node_modules/leaflet/dist/leaflet.css"
            ],
            "scripts": []
          },
          ...
        }
      }
    }
}

You will need to restart the dev server to apply changes from angular.json.

Add a Leaflet map to an Angular-component

Open MyMapComponent if you use our template or create a new component.

  • Remove placeholder and create ViewChild for the div element. Add ngAfterViewInit() lifecycle hook that is called after Angular has fully initialized a component’s view:
<div class="map-container" #map></div>
import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-my-map',
  templateUrl: './my-map.component.html',
  styleUrls: ['./my-map.component.scss']
})
export class MyMapComponent implements OnInit, AfterViewInit {

  @ViewChild('map')
  private mapContainer: ElementRef<HTMLElement>;

  constructor() { }

  ngOnInit() {
  }

  ngAfterViewInit() {
  }
}
  • Add a Leaflet map to the component:
import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import  * as L from 'leaflet';
import 'mapbox-gl-leaflet';

@Component({
  selector: 'app-my-map',
  templateUrl: './my-map.component.html',
  styleUrls: ['./my-map.component.scss']
})
export class MyMapComponent implements OnInit, AfterViewInit {

  private map: L.Map;

  @ViewChild('map')
  private mapContainer: ElementRef<HTMLElement>;

  constructor() { }

  ngOnInit() {
  }

  ngAfterViewInit() {
    const myAPIKey = "YOUR_API_KEY_HERE";
    const mapStyle = "https://maps.geoapify.com/v1/styles/osm-carto/style.json";

    const initialState = {
      lng: 11,
      lat: 49,
      zoom: 4
    };

    const map = new L.Map(this.mapContainer.nativeElement).setView(
      [initialState.lat, initialState.lng],
      initialState.zoom
    );

    // the attribution is required for the Geoapify Free tariff plan
    map.attributionControl
      .setPrefix("")
      .addAttribution(
        'Powered by <a href="https://www.geoapify.com/" target="_blank">Geoapify</a> | © OpenStreetMap <a href="https://www.openstreetmap.org/copyright" target="_blank">contributors</a>'
      );

    L.mapboxGL({
      style: `${mapStyle}?apiKey=${myAPIKey}`,
      accessToken: "no-token"
    }).addTo(map);
  }
}

Build the application

Run ng build to build the project. The build artifacts will be stored in the dist/ directory. Use the --prod flag for a production build.

More code sample

Find more Live demos, JSFiddle samples and Code samples on the Geoapify API Documentation page.