Display all locations within the boundaries of the maps in Angular using Google Maps

I have integrated the following Framework into my Angular 6 project:

This is my first Angular project, so I am still navigating my way through it. The current status of my project is as follows: I have successfully loaded the map with a specific location as the center. The map is loading markers and clustering them when zooming out. There is a side menu listing all marker items with information about the location. I have also implemented user interaction functionalities: Hovering over a marker or list item in the side menu highlights the corresponding item in the list/map. Additionally, clicking on a marker or list item reveals detailed information in the side menu. So far, everything is working well.

Now, I aim to extract all markers located within the current bounds of the map to shorten the list in the side menu. In the component's template, I am using the map as shown below (extracted section):

[...]

<!-- Map Section -->
<div class="main-data-container content-box">
  <div class="split-view-container" #parentData>
    <app-spinner *ngIf="!allItems"></app-spinner>
    <agm-map [style.height.px]="parentData.offsetHeight"
             [latitude]="mapCenter.lat"
             [longitude]="mapCenter.lon"
             [zoom]="mapZoom"
             #agmMap>
      <agm-marker-cluster [styles]="[companyStyle]">
        <agm-marker
          *ngFor="let companyLocation of companyLocations"
          (markerClick)="clickedMarker(companyLocation)"
          (mouseOver)="hoverOverMarker(companyLocation)"
          (mouseOut)="hoverOutMarker(companyLocation)"
          [latitude]="companyLocation.latitude"
          [longitude]="companyLocation.longitude"
          [iconUrl]="{url: setIcon(companyLocation), scaledSize: {width: 55, height: 82.5}}">
        </agm-marker>
      </agm-marker-cluster>
    </agm-map>
  </div>

  [...]

companyLocations: An array in the TypeScript document that contains information about various company locations.

#agmMap: Used to bind the HTML element to an object in the TypeScript file.

Now, onto the TypeScript section where I am facing challenges:

[...]

@ViewChild('agmMap') agmMap: any;

companyLocations: Array<CompanyLocation>;

filteredCompanyLocations: Array<CompanyLocation>;

[...]

checkMarkersInBounds() {

    // Initialize Filtered Arrays as empty Arrays
    this.filteredCompanyLocations = [];

    // Iterate through all CompanyLocations
    for(let company of this.companyLocations){

      // Write coordinates from companyLocation into LatLng Object 
      let loc: LatLngLiteral = {lat: company.latitude, lng: company.longitude};

      // Check if the Location is in Bounds of the Map
      if (this.agmMap.getBounds().contains(loc)){

        // If it's in Bounds, add it to the filtered Array
        this.filteredCompanyLocations.push(company);

      }
    }
  }

[...]

I am encountering an error with .getBounds():

TypeError: this.agmMap.getBounds is not a function.

When I attempt to replace

this.agmMap.getBounds().contains(loc)
with
this.agmMap._mapsWrapper.getBounds().contains(loc)
, it throws:

TypeError: this.agmMap._mapsWrapper.getBounds(...).contains is not a function.

I have tried several solutions from various sources for similar scenarios, but have not been able to find a resolution:

I would appreciate any tips or solutions that can be provided. I have been struggling with this for days and may be missing something crucial to solve the issue...

Answer â„–1

After much trial and error, I came up with a solution to tackle this issue. To address this in the Template, I included an event output to the (boundsChange) Output of the map. This feature returns the bounds of the map and triggers whenever there is a change in the bounds:

[...]
<agm-map
        [style.height.px]="parentData.offsetHeight"
        [latitude]="mapCenter.lat"
        [longitude]="mapCenter.lon"
        [zoom]="mapZoom"
        (boundsChange)="processBoundsChange($event)">
[...]

Within the TS (TypeScript) file, I created the processBoundsChange(bounds) Method to handle this functionality:

processBoundsChange(bounds) {

    this.filteredItems = [];

    for(let location of this.businessLocations){

      let locationCoords = {lat: location.latitude, lng: location.longitude};

      if (bounds.contains(locationCoords)){

        //Add the item to an array for display in the list

      }
    }
  }

Answer â„–2

In case the unfiltered list is extensive, considering the inclusion of a debounce timer is advisable.

  private debounceTimer = null;

  public checkMarkersInBounds(bounds: any): void {
    // The debounce timer ensures that marker filters are not processed until the map remains stationary for 200ms
    if (this.debounceTimer !== null) {
      clearTimeout(this.debounceTimer);
      this.debounceTimer = null;
    }
    this.debounceTimer = setTimeout(() => {
      this.companyFilter = [];
      for (const companyof this.companyLocations) {
        if (bounds.contains({ lat: company.lat, lng: company.long })) {

          // Add the item to an Array that will be displayed in the List

        }
      }

    }, 200);
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the power of async/await and promise in TypeScript

I'm puzzled as to why the return type string in this method is showing up as a red error: exportPageAsText(pageNumber: number): string { (async () => { const text = await this.pdfViewerService.getPageAsText(pageNumber); ...

Spring Boot + Angular: missing required parameter is causing an issue

When working on my project, I encountered an issue with sending a POST request from the client side in Angular to a server based on Spring Boot. Here is the code snippet I used: const headers = new HttpHeaders().set( "Content-Type", "app ...

How to resolve the 'TypeError: Cannot read property 'type' of undefined' error when running tests with Jest for i18next

I've been working on a React project where I implemented i18next version 15.0.4 and react-i18next version 10.2.0 as dependencies. To handle internationalization, I created a module that initializes i18next with react-i18next and now I'm trying to ...

Is it possible to use Immutable named parameters with defaults in Typescript during compilation?

Here is an example that highlights the question, but unfortunately it does not function as intended: function test({ name = 'Bob', age = 18 }: { readonly name?: string, readonly age?: number }) { // this should result in an error (but doesn&apo ...

Is there a comparable alternative to <ion-forward>?

I have a brand new module where users input information across 3 separate pages. Page 1: basic details with a continue button Page 2: additional info with another continue button and Page 3: the final submission Currently, when navigating back from Page ...

What is the best way to extract a value from an input tag within a TSX component and then utilize that value in a Node JS file located in a separate directory?

Currently, I'm immersed in a personal project where I'm utilizing Fetch to pull data from an API. The challenge I'm facing involves sending a call from my index.js file to a TSX component when a SearchButton component is clicked. However, th ...

What is the proper type for an object and an array of strings?

We have an array example below. const sampleArray = [ {names: ['example1', 'example2']}, 'another', 'final' ]; Additionally, here is a type error example. The error message reads as follows: "Type 'string ...

What is the best way to adjust the output size for ngx-webcam?

I am looking to determine the smallest possible size for an image that is captured. From my testing with ngx-webcam, I have found that I can adjust the minimum height of the output image based on the display height of the webcam. Is there a method to set ...

"Enhance your Vue 3 projects with a dynamic library featuring universal components and full

Currently, I am in the process of developing a Vue 3 component library using Vue 3, Vite, and TypeScript. The unique aspect about this library is that it installs as a plugin and registers all components as global entities. Here is an overview of how this ...

Troubleshooting Authorization Header Issue in Angular 5

I created an Interceptor to include an Authorization token in all HTTP Requests, but unfortunately it's not functioning as expected. I've double-checked my code and everything seems correct, so I'm wondering if there's something crucial ...

NPM IP library susceptible to Server-Side Request Forgery (SSRF) vulnerabilities

Received Security Alert from GitHub's Dependabot Regarding an Issue in My Angular Repository A security vulnerability has been identified in all versions of the NPM package "ip," allowing a malicious actor to execute arbitrary code and access sensiti ...

Is there a way to access the result variable outside of the lambda function?

My goal is to retrieve data from an external API using Typescript. Below is the function I have written: export class BarChartcomponent implements OnInit{ public chart: any; data: any = []; constructor(private service:PostService) { } ngOnInit( ...

Function editing error

Attempting to retrieve user data for editing in the form is causing an error related to the line where the data is being assigned: **** this.user = data This is the content of edit-user.component.ts: import { Component, OnInit } from '@angular/core ...

Tips for Looping through an Object within another Object

Is there a way to retrieve values from an Object that contains another Object nested inside? I am not overly concerned about the keys, but it would be helpful if I could access them as well. Here is an example of the response: res = {data: {name: 'na ...

What is the best way to list the choices associated with a specific category?

The Node.js package I'm currently working with requires an argument of a specific type, which I can see is defined through a TypeScript declaration as follows: export declare type ArgType = 'A' | 'B' | 'C'; I am interes ...

Issue with PassportJS and Express 4 failing to properly store cookies/session data

I have a situation with my Express 4 app using Passport 0.3.2. I've set up a passport-local strategy, and it's successfully retrieving the user information when the /session endpoint is provided with a username and password. The issue arises whe ...

What could be causing my SectionList to occasionally display only a single section?

I'm facing a problem with the SectionList component where it occasionally fails to display all sections, only rendering the first one. After some debugging, I may have found a solution, but I'm unsure why it resolves the issue. While my page con ...

Issue with aliasing in tsconfig.app.json not functioning correctly in Angular 11

I'm facing a problem with aliasing after migrating my application to an Angular project. None of my imports are functioning properly with the ""@app"" alias. mainApp │ package.json │ tsconfig.json │ angular.json │ └─┠...

Exploring the power of flow.js within an Angular 2 Typescript project

I am trying to incorporate flowjs or ng-flow into my Angular 2 application. After installing the flowjs typings using npm install --save-dev @types/flowjs from However, upon importing it into my component with import { Flow } from 'flowjs';, ...

NPM INSTALL will not regenerate .js files from .ts files

I am having issues compiling my angular2/typescript files into javascript files. After running "npm install" without any warnings or errors, the node_modules directory is created. However, the .js files are not being recreated from my .ts files and the an ...