Google Maps in Angular with Google Maps Javascript API

Syed Nafees Aslam
4 min readMay 5, 2024

--

Google Maps Javascript Api in Angular

In today’s digital age, location-based services are an integral part of many web and mobile applications. Whether you’re building a travel app, a food delivery platform, or a real estate website, integrating maps and location-based features can enhance the user experience and provide valuable functionality. Google Maps is one of the most popular mapping platforms, and in this blog post, we’ll explore how to integrate Google Maps with the AutoComplete Places API in an Angular application.

Goals

  1. Show a custom draggable marker on the map to get a precise location.
  2. Drag the marker to change/update the location.

Prerequisites

Before we dive into the implementation details, make sure you have the following prerequisites in place:

  1. Angular CLI Installed on your system. If not already done click here.
  2. Angular Basics ( What and How in Angular). Visit if you are a beginner in Angular
  3. Google Developer Account. Click to create one.
  4. Maps API KEY. Get or Generate New here.
  5. MapID(create in Google Console) attached to a VectorMap( For Data and Event Driven Map Integration).
  6. Google Maps Javascript API Documentation ( For Reference and better understanding). Goto Documentation.
  7. @googlemaps/js-api-loader npm package goes well with Angular.

Integrating Google Map

Step 1: Install NPM Package and Load Google Maps JavaScript API

Open a new terminal window and navigate to your project root folder. Then type the below written command to install the package.

npm install @googlemaps/js-api-loader 

Once the package is installed successfully. Import the package within the intended Component (e.g.: AddressComponent). Use the below code to import the package.

import { Loader } from "@googlemaps/js-api-loader"

Now you need to load the map in the component using the code below. In Order to load the map successfully you need Maps API_KEY.

// SNIP_1 START
const loader = new Loader({
apiKey: "GOOGLE_MAPS_API_KEY",
libraries:["places"],
version: "weekly"
});
// SNIP_1 END

Now you are ready to load the map on the DOM. Follow the Snippet below.

// SNIP_2 START
loader.load().then(async()=>{
// You can assign any prefered lat,lng combination to the variables
// respectively or you can prompt for current location.
// for testing purpose you use this lat: 25.160808, lng: 75.854828
const myLatlng = { lat: InitialLatitude, lng: InitialLongitude };

// Target the HTML Element with id="map" where the map will be rendered
// eventually.
let mapDisplayArea:any = document.getElementById("map");

// COPY & PASTE SNIP_3 HERE.
})
// SNIP_2 END

Finally you need to load Map Class to render the map on the DOM.

// SNIP_3 START
const map = new google.maps.Map(mapDisplayArea, {
mapId:"MAP_ID(Attached to a vector map)",
zoom: 14,
center: myLatlng,
// Removing Controls and buttons from the map
mapTypeControl:false,
fullscreenControl:false,
scaleControl:false,
streetViewControl:false
});
// SNIP_3 END

If you have caught up till here you must be seeing a beautiful vector map on your device screen and you have already completed the STEP 1.

In the next step we are going to customize the marker icon. Let’s quickly jump to next step and get the job done.

Custom Marker Icon

Step 2: Customising Marker Icon and making the marker draggable.

In order to create a custom marker in google maps we need to create a new Marker object provided by google maps. see the code below..


//SNIP_4 START
const marker = new google.maps.Marker({
map,
icon:'../../../assets/pins/map-pin.png',
animation: google.maps.Animation.DROP,
position:myLatlng,
draggable:true,
crossOnDrag:true,
anchorPoint: new google.maps.Point(0, -29),
});

//SNIP_4 END

Create a new Marker object as shown in the above snippet [SNIP_4]. We need to pass some values in order to initialise the marker object.

  1. pass the above create map object to the marker so that rendered marker display in the middle of the same map instance [ Marker references LatLng Center from the map options passed in]
  2. A custom marker image.png [ not sure if other image extensions are supported by google maps or not, play around to check ].
  3. Loading Animation type : In my case I am using DROP [Check Docs for other animation interfaces ] animation interface provided by google maps. When the map is loaded on DOM marker appears with drop animation [ fall from top to center of map]. While other options are also worth trying.

Now that our custom marker is ready. We need to add an EventListener on marker in order to get the exact location. When the user drags the marker.


//SNIP_5 START
marker.addListener('dragend',(event:any) =>{
const position:any = map.getCenter()
// console.log(event.latLng.lat());
// console.log(position.lat());

this.fetched_lat_lng = {
lat: position.lat(),
lng: position.lng()
}

const myLatlng = new google.maps.LatLng(event.latLng.lat(),event.latLng.lng())
map.setCenter(event.latLng);
map.setZoom(17);
marker.setPosition(myLatlng);
setTimeout(() => {
map.panTo(myLatlng);
}, 500);
});

//SNIP_5 END

The above snippet clearly explains an EventListener is attached “dragend” event which simply listens to the marker drag end event from the DOM. Then we can get the updated postion of the marker with map.getCenter() method.

Finally we need to initialise a new latLng literal using

new google.maps.LatLng(lat,lng)

Then

  1. Reinitialise map center by passing lat,lng to map.setCenter(event.latLng)
  2. Set map zoom map.setZoom(17)
  3. Set marker to updated position by marker.setPosition(myLatlng)
  4. Last but not the least use map.panTo(myLatlng ) to cover the transition by animation.

Thanks, I hope this post might helpful. Acknowledge the post & motivate me for more posts like this by claps and comments.

Suggestions and feedbacks welcomed

--

--