Summary
Google Maps integration with polylines in an Angular app involves creating a web application that utilizes the Google Maps JavaScript API to display maps and draw polylines. Polylines are lines drawn on the map to represent routes, paths, or any connected sequence of points. Here's a concise summary of the process:
Hello there, so I needed to use Google Maps in my Angular App and found a couple of Third Party Libraries which were really good, an example of that would be Angular Google Maps (AGM).
Table of contents
- Prerequisites.
- Markers & polylines on destinations.
- Adding markers to the array.
- Advanced prototyping
- Overall User Experience
- Conclusion
1. Prerequisites
- Node installed on your machine
- NPM installed on your machine
- Installing Angular CLI 10: npm install -g @angular/cli
- Creating your Angular 10 Project: ng new angular-example
Now, I’m assuming you already have your Angular application set up and your google maps API key. If not, go do that quickly and come back here.
You can get your API Key here.
https://developers.google.com/maps/documentation/javascript/get-api-key
First, import the Google Maps SDK in your index.html.You must include your API Key in the script tag as shown below.
Next, install Google Maps & AGM packages.
npm i @angular/google-mapsnpm i @agm/corenpm i @types/googlemaps
That’s it for the setup, now let’s get to the cool stuff.
Okay, create a wrapper for the map in your component’s HTML file.
OR you can directly place tag and give it any height according to your requirement.
You can assign Zoom any integer value according to your convenience.
Finally, do the magic in the component’s TS file.
To create a class variable that we can use to access the map instance,
To create an element reference to the map wrapper in the HTML file,
I’m sure you’re familiar with angular’s ngAfterViewInit() function or lifecycle hook, which is a callback method of angular’s AfterViewInit abstract class that is invoked immediately after Angular has completed the initialization of a component’s view. It is invoked only once when the view is instantiated. So the function initializeMap() is called when the component’s view has been initialized.
So let’s demystify the initializeMap() function.
const bounds = new google.maps.LatLngBounds();
This will bring Google Maps on your screen.
2. MARKERS & POLYLINES ON DESTINATIONS:
Now to get to the current position and add a marker on it,
Load this function on ngOnInit() of the component and give this center position to attribute in the center in the google-map component. HTML will show the current location as soon as the component gets loaded.
3. Adding markers to the array
As you add the destinations from the input shown above, it keeps pushing it into the array which will contain each marker with its coordinates of the latitude & longitude.
To connect the lines joining each marker we use which has the options attribute. Here we have defined options as,
Top comments (0)