• Stars
    star
    165
  • Rank 228,906 (Top 5 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 6 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Autocomplete input component and directive for google-maps built with angular and material design |

angular-material-extensions's logo

@angular-material-extensions/google-maps-autocomplete - Autocomplete input component for google-maps built with angular material design

npm version npm demo Join the chat at https://gitter.im/angular-material-extensions/Lobby Coverage Status Build Status CircleCI branch Greenkeeper Badge license Awesome

@angular-material-extensions/google-maps-autocomplete

@angular-material-extensions/google-maps-autocomplete

Please use lib v8 only with angular v15

Built by and for developers ❀️

Do you have any question or suggestion ? Please do not hesitate to contact us! Alternatively, provide a PR | open an appropriate issue here

If did you like this project, support angular-material-extensions by starring ⭐ and sharing it πŸ“’

Table of Contents

Demo

View all the directives and components in action at https://angular-material-extensions.github.io/google-maps-autocomplete

Dependencies

  • Angular (requires Angular latest | we are using already v15 ;)

for the directive as standalone you just need to install the agm core module

npm i @agm/core 

optional

npm i -D @types/googlemaps 

Installation

1. Install via ng add. (Recommended)

If Angular Material Design is not setup, just run ng add @angular/material learn more

Now add the library via the angular schematics and everything will be setup for you

ng add @angular-material-extensions/google-maps-autocomplete

2. Install via npm. (Alternative)

Now install @angular-material-extensions/google-maps-autocomplete via:

npm install --save @angular-material-extensions/google-maps-autocomplete

Requirements (peer dependencies):

for the ui input component, please consider installing the following packages

npm i @angular/cdk @angular/material @angular/animations @angular/forms 

Additional requirements Theme (Material Design)


SystemJS

Note:If you are using SystemJS, you should adjust your configuration to point to the UMD bundle. In your systemjs config file, map needs to tell the System loader where to look for @angular-material-extensions/google-maps-autocomplete:

{
  '@angular-material-extensions/google-maps-autocomplete';
:
  'node_modules/@angular-material-extensions/google-maps-autocomplete/bundles/google-maps-autocomplete.umd.js',
}

Once installed you need to import the main module:

import {MatGoogleMapsAutocompleteModule} from '@angular-material-extensions/google-maps-autocomplete';

The only remaining part is to list the imported module in your application module. The exact method will be slightly different for the root (top-level) module for which you should end up with the code similar to ( notice MatGoogleMapsAutocompleteModule.forRoot()):

import {AgmCoreModule} from '@agm/core';
import {MatGoogleMapsAutocompleteModule} from '@angular-material-extensions/google-maps-autocomplete';

@NgModule({
  declarations: [AppComponent, ...],
  imports: [
    // important !!!
    AgmCoreModule.forRoot({
      apiKey: 'YOUR_KEY',
      libraries: ['places']
    }),
    MatGoogleMapsAutocompleteModule, ...],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Other modules in your application can simply import MatGoogleMapsAutocompleteModule:

import {MatGoogleMapsAutocompleteModule} from '@angular-material-extensions/google-maps-autocomplete';

@NgModule({
  declarations: [OtherComponent, ...],
  imports: [
    MatGoogleMapsAutocompleteModule, ...],
})
export class OtherModule {
}

Usage

As directive

add matGoogleMapsAutocomplete to your target html input element to enable the google maps autocomplete api as feature

<mat-form-field>
  <mat-label>Address << using the directive >></mat-label>
  <input matInput
         matGoogleMapsAutocomplete
         [country]="de"
         (onAutocompleteSelected)="onAutocompleteSelected($event)"
         (onLocationSelected)="onLocationSelected($event)">
</mat-form-field>

As components

or alternatively use mat-google-maps-auto-complete, the UI wrapper

add mat-google-maps-auto-complete element to your template

mat-google-maps-auto-complete

<mat-google-maps-autocomplete [appearance]="appearance.OUTLINE"
                              (onAutocompleteSelected)="onAutocompleteSelected($event)"
                              (onLocationSelected)="onLocationSelected($event)">
</mat-google-maps-autocomplete>

A customized mat-google-maps-autocomplete

<mat-google-maps-autocomplete country="us"
                              type="address"
                              (onAutocompleteSelected)="onAutocompleteSelected($event)"
                              (onLocationSelected)="onLocationSelected($event)">
</mat-google-maps-autocomplete>

combine the result of the mat-google-maps-autocomplete with a google map instance via @agm

<div class="container" fxLayout="column" fxLayoutAlign="center">

  <div fxFlex>
    <agm-map [latitude]="latitude" [longitude]="longitude" [scrollwheel]="false" [zoom]="zoom">
      <agm-marker [latitude]="latitude" [longitude]="longitude"></agm-marker>
    </agm-map>
  </div>

  <div fxFlex fxFlexAlign="center"
       class="autocomplete-container"
       [ngStyle.xs]="{'min-width.%': 100}"
       [ngStyle.sm]="{'width.%': 70}">
    <mat-google-maps-autocomplete (onAutocompleteSelected)="onAutocompleteSelected($event)"
                                  (onLocationSelected)="onLocationSelected($event)"
                                  (onGermanAddressMapped)="onGermanAddressMapped($event)">
    </mat-google-maps-autocomplete>
  </div>

</div>

in your component, the code will be similar to -->

import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {Title} from '@angular/platform-browser';
import {Location, Appearance, GermanAddress} from '@angular-material-extensions/google-maps-autocomplete';
import {} from '@types/googlemaps';
import PlaceResult = google.maps.places.PlaceResult;

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class HomeComponent implements OnInit {

  public appearance = Appearance;
  public zoom: number;
  public latitude: number;
  public longitude: number;
  public selectedAddress: PlaceResult;

  constructor(private titleService: Title) {
  }

  ngOnInit() {
    this.titleService.setTitle('Home | @angular-material-extensions/google-maps-autocomplete');

    this.zoom = 10;
    this.latitude = 52.520008;
    this.longitude = 13.404954;

    this.setCurrentPosition();

  }

  private setCurrentPosition() {
    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition((position) => {
        this.latitude = position.coords.latitude;
        this.longitude = position.coords.longitude;
        this.zoom = 12;
      });
    }
  }

  onAutocompleteSelected(result: PlaceResult) {
    console.log('onAutocompleteSelected: ', result);
  }

  onLocationSelected(location: Location) {
    console.log('onLocationSelected: ', location);
    this.latitude = location.latitude;
    this.longitude = location.longitude;
  }

  onGermanAddressMapped($event: GermanAddress) {
    console.log('onGermanAddressMapped', $event);
  }

}

Reactive Forms Example

<form [formGroup]="addressFormGroup">
  <mat-search-google-maps-autocomplete formControlName="address">
  </mat-search-google-maps-autocomplete>

  // OR

  <mat-google-maps-autocomplete formControlName="address">
  </mat-google-maps-autocomplete>

</form>
import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';

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

  addressFormGroup: FormGroup;

  ngOnInit(): void {
    this.addressFormGroup = new FormGroup({
      address: new FormControl(),
    });

    this.addressFormGroup.get('address').valueChanges.subscribe(value => console.log('value changed', value))
  }
}

API - for more info please visit the official documentation Maps JavaScript API

matGoogleMapsAutocomplete

option bind type default description
value Input() PlaceResult ; -
address Input() PlaceResult string; -
country Input() string string[]; -
placeIdOnly Input() boolean - can be used to instruct the Autocomplete widget to retrieve only Place IDs. On calling getPlace() on the Autocomplete object, the PlaceResult made available will only have the place id, types and name properties set. You can use the returned place ID with calls to the Places, Geocoding, Directions or Distance Matrix services.
strictBounds Input() boolean - is a boolean specifying whether the API must return only those places that are strictly within the region defined by the given bounds. The API does not return results outside this region even if they match the user input.
types Input() string[] - An array of types specifies an explicit type or a type collection, as listed in the supported types below. If nothing is specified, all types are returned. In general only a single type is allowed. The exception is that you can safely mix the geocode and establishment types, but note that this will have the same effect as specifying no types. Supported types are listed below.
type Input() string -
autoCompleteOptions Input() AutocompleteOptions - all above inputs in one object! The passed data to this object will be merged with the input if they exists
onChange Output() PlaceResult string null
onAutocompleteSelected Output() PlaceResult - the event will be fired when a place has been selected via the google maps autocomplete component
onGermanAddressMapped Output() GermanAddress - the event will be fired when a place has been selected and mapped to the german address interface
onLocationSelected Output() Location - the event will be fired when a place has been selected via the google maps autocomplete component

Supported Types

type description
geocode instructs the Places service to return only geocoding results, rather than business results.
address instructs the Places service to return only geocoding results with a precise address.
establishment instructs the Places service to return only business results.
regions instructs the Places service to return any result matching the following types: locality, sublocality, postal_code, country, administrative_area1, administrative_area2
cities instructs the Places service to return results that match either locality or administrative_area3.

mat-google-maps-autocomplete

everything included in matGoogleMapsAutocomplete + the following

option bind type default description
addressLabelText Input() string; Address using the component self explanatory
placeholderText Input() string; Please enter the address self explanatory
requiredErrorText Input() string; The address is required self explanatory
invalidErrorText Input() string; The address is not valid self explanatory
appearance Input() Appearance string; Appearance.STANDARD

mat-search-google-maps-autocomplete

option bind type default description
searchBarAppearance Input() Appearance string; Appearance.STANDARD
appearance Input() Appearance string; Appearance.STANDARD
searchAddressLabel Input() string; Search Address input label
streetNameLabel Input() string; Street input label
streetNumberLabel Input() string; Nr. input label
postalCodeLabel Input() string; PLZ input label
vicinityLabel Input() string; Locality input label
localityLabel Input() string; Locality input label
showVicinity Input() boolean; false input label - whether to display the vecinity
readonly Input() boolean; false readonly input
disableSearch Input() boolean; false disabled users to search a place
value Input() GermanAddress; - the initial value of the component
country Input() string string[]; -
placeIdOnly Input() boolean - can be used to instruct the Autocomplete widget to retrieve only Place IDs. On calling getPlace() on the Autocomplete object, the PlaceResult made available will only have the place id, types and name properties set. You can use the returned place ID with calls to the Places, Geocoding, Directions or Distance Matrix services.
strictBounds Input() boolean - is a boolean specifying whether the API must return only those places that are strictly within the region defined by the given bounds. The API does not return results outside this region even if they match the user input.
types Input() string[] - An array of types specifies an explicit type or a type collection, as listed in the supported types below. If nothing is specified, all types are returned. In general only a single type is allowed. The exception is that you can safely mix the geocode and establishment types, but note that this will have the same effect as specifying no types. Supported types are listed below.
type Input() string -
onGermanAddressMapped Output() EventEmitter string; Appearance.STANDARD

@angular-material-extensions/google-maps-autocomplete

<mat-card>
  <mat-card-title>Auto Parse Address</mat-card-title>
  <mat-card-content>
    <!-- #######   here we go !! ######-->
    <mat-search-google-maps-autocomplete appearance="outline"
                                         country="de"
                                         (onGermanAddressMapped)="onGermanAddressMapped($event)">
      >
    </mat-search-google-maps-autocomplete>
  </mat-card-content>
</mat-card>
import {Appearance, GermanAddress, Location} from '@angular-material-extensions/google-maps-autocomplete';

onGermanAddressMapped($event;
:
GermanAddress;
)
{
  console.log('onGermanAddressMapped', $event);
}

Documentation

Please checkout the full documentation here or follow the official tutorial

Run Demo App Locally

$ git clone https://github.com/angular-material-extensions/google-maps-autocomplete.git
  • link the @angular-material-extensions/google-maps-autocomplete package
$ gulp link
  • navigate to the demo app directory, install the dependencies and serve the app
$ cd demo && npm i && npm start
  • the app is now hosted by http://localhost:4200/

Development

  1. clone this repo
  2. Install the dependencies by running npm i
  3. go to lib directory under projects/angular-material-extensions/google-maps-autocomplete
  4. build the library npm run build

Other Angular Libraries


Support

Built by and for developers ❀️ we will help you πŸ‘Š


Who is using ngx-mailto? Awesome apps?

  1. Nahaus.de

Are you missing your project or you app? PR me to publish it on the README


License

Copyright (c) 2019-2022 Anthony Nahas. Licensed under the MIT License ( MIT)

angular-material-extensions's logo

More Repositories

1

password-strength

Angular UI library to illustrate and validate a password's strength with material design
TypeScript
276
star
2

select-country

Angular Material component that allow users to select a country or nationality with an autocomplete feature
TypeScript
118
star
3

link-preview

Angular open source UI library to preview web links
JavaScript
56
star
4

pages

Open source library for angular apps to illustrate custom material pages content with steps (ideal for tutorials and explanations purposes)
CSS
50
star
5

fab-menu

Angular Component that represents a menu of buttons triggered by a floating action button | built with material design
TypeScript
48
star
6

freelancer-theme

Open Source Angular Material Theme as SPA for freelancers based on Start Bootstrap Theme
TypeScript
48
star
7

contacts

Angular Library to manage contacts and users with a material design
JavaScript
44
star
8

faq

Angular Library built with material design in order to provide a reusable faq (frequently asked questions) component for every project. Ask, Answer and List
JavaScript
29
star
9

calendar

Angular responsive calendar built with material design for desktop and mobile
TypeScript
21
star
10

jumbotron

Angular UI open source library built with material design in order to illustrate a highlighted/important information for the user
JavaScript
7
star
11

core

Set of components, directives and services to boost the app development with angular material 2
TypeScript
7
star
12

select-icon

Angular component that allows to select an option in form of a material design icon button
TypeScript
6
star
13

components

Set of components, directives, services and modules to boost the app development with angular material
CSS
5
star
14

layout

Set of angular directives that allow developers to boost and easy enhance their app development's layout
JavaScript
5
star
15

input-counter

Modern number input component built with angular and material design
HTML
3
star
16

algolia

Angular Material Components for Algolia Instant Search | Search, Autocomplete, Query, Filter
TypeScript
1
star
17

loaders

Set of angular loading components - simple and easy to use
HTML
1
star