'Why is the google maps places search not placing a marker when a location is found in my Angular project?

I am using the @angular/google-maps package in my Angular project to display a map with a search box for searching locations. When I search for a location, it is displaying the location in the map but it is not highlighting the location with a marker. I have followed all the guidelines provided by google maps documentation. Below is my code.

App.component.html :

<input #search class="form-control" type="text">
<google-map
    width="100%"
    [center]="currentLocation"
    [options]="mapConfigurations"
></google-map>

App.component.ts :

import { Component, ElementRef, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { GoogleMap } from '@angular/google-maps';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterViewInit {
  @ViewChild('search') searchField!: ElementRef;
  @ViewChild(GoogleMap) map: google.maps.Map;
  title = 'car-booking-frontend';
  currentLocation: any;
  mapConfigurations: any;
  constructor(){}

  ngOnInit(): void {
    this.mapConfigurations = {
      disableDefaultUI: true,
      fullscreenControl: true,
      zoomControl: true
    };
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((position)=> {
        this.currentLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      });
    }
  }

  ngAfterViewInit() {
    const searchBox = new google.maps.places.SearchBox(this.searchField.nativeElement);

    this.map?.controls[google.maps.ControlPosition.TOP_CENTER].push(this.searchField.nativeElement);
    

    let markers: google.maps.Marker[] = [];

    searchBox.addListener('places_changed', () => {
      const places: any = searchBox.getPlaces();

      if (places.length === 0) {
        return;
      }

      markers.forEach((marker) => {
        marker.setMap(null);
      });
      markers = [];

      const bounds = new google.maps.LatLngBounds();
      places.forEach((place: any) => {
        if (!place.geometry || !place.geometry.location) {
          return;
        }

        const icon = {
          url: place.icon as string,
          size: new google.maps.Size(71, 71),
          origin: new google.maps.Point(0, 0),
          anchor: new google.maps.Point(17, 34),
          scaledSize: new google.maps.Size(25, 25),
        };
        markers.push(
          new google.maps.Marker({
            map:this.map,
            icon:icon,
            title: place.name,
            position: place.geometry.location,
          })
        );

        if (place.geometry.viewport) {
          bounds.union(place.geometry.viewport);
        }
        else {
          bounds.extend(place.geometry.location);
        }
      });
      this.map?.fitBounds(bounds);
    });
  }  
}

App.module.ts :

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>CarBookingFrontend</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script async src="https://maps.googleapis.com/maps/api/js?key={MY_API_KEY}&libraries=places">
  </script>
</head>
<body>
  <app-root></app-root>
</body>
</html>

While running this, I am able to search for locations, but the locations are not highlighted with markers as shown in google places search box. Instead I am getting an error in the browser console as follows: InvalidValueError: setMap: not an instance of Map; and not an instance of StreetViewPanorama

Please suggest the required changes.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source