Deactivating Google Map Clustering for Individual Markers

I'm currently utilizing Angular 4, Google Maps v3, and Marker Clusterer v2 - all of which are the latest versions. I'm attempting to implement a straightforward example found in the official Google Maps documentation (https://developers.google.com/maps/documentation/javascript/marker-clustering) to cluster and un-cluster my markers.

Map initialization is nothing out of the ordinary:

public ngOnInit(): void {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 7,
    center: {lat: 41.85, lng: -87.65}
  });
  this.generateMockPinResultsResponse(10000, map);
}

This function called during initialization generates sample pins:

  public generateMockPinResultsResponse(nMarkers, map): void {
    let component = this;
    var markers = [];
    for (var i = 0; i<nMarkers; i++){
      let latitude: number = this.getRandomUsLat();
      let longitude: number = this.getRandomUsLng();
      var marker = new google.maps.Marker({
        position: { lat: latitude, lng: longitude },
        map: map
      });
      markers.push(marker);
    }
    var markerCluster = new MarkerClusterer(map, markers);//
  }

The provided code above contains all relevant information. While my markers do cluster successfully, they fail to uncluster, and I am unsure why. You can find my partially functioning code here: PLUNK, with the code snippets located in the app.ts file.

Edit: The map does uncluster into smaller clusters, but it does not uncluster into individual pins.

Answer №1

By tracking your locations, it becomes apparent that a random lng/lat to 0 decimal places results in duplicate coordinates when generating 10,000 locations. Click here for more information.

const positions = markers.map(marker => {
  const position = marker.getPosition();

  return {
    lat: position.lat(),
    lng: position.lng(),
})

console.log(positions);

Improving the generator to create better (to 4 decimal places) random locations resolves this issue. Check out the changes here.

public getRandomInRange (from, to, fixed) {
    return (Math.random() * (to - from) + from).toFixed(fixed) * 1;
  }

  private getRandomUsLat(){
    let max = 48;
    let min = 30;
    let num = this.getRandomInRange(min, max, 4);

    return num;
  }

  private getRandomUsLng(){
    let max = -70;
    let min = -110;
    let num = this.getRandomInRange(min, max, 4);
    return num;
  }

Answer №2

Angular is not to blame for the issue at hand. The randomly generated function for latitude and longitude can sometimes result in multiple markers being very close to each other on the map. This causes confusion for the Google map library.

To see an example, you can check out this Plunker. Additionally, this problem has been reported on Github.

In my Plunker with only 1000 items, you can still observe the issue. Some suggest adjusting the max zoom of the map object, but this solution may vary depending on the map type as stated in the Google Maps documentation.

If your data requires clustering of closely located markers, you might consider using Leaflet instead of Google Maps.

A user who faced a similar challenge with the Google Maps API shared their experience:

This issue, along with many other limitations in the Google Maps API requiring workarounds forced our business away from Google Maps. We're now using Leaflet and Mapbox with great success.

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

What is the best method for arranging components?

I have a Product component that contains crucial information about various products. Adjacent to this data, there is a separate component called Buttons, which includes two buttons - one for adding the product to a favorites list and another for adding it ...

The Google Maps API swipe feature on mobile devices is causing issues with screen scrolling

When users visit my website on mobile, they encounter a situation where Google Maps suddenly covers the entire page, preventing them from scrolling away. This is because swiping up or down only moves the map view within Google Maps, instead of scrolling th ...

"An error occurred in Angular due to the absence of a defined user

Creating a variable boolean isEdit in Angular8 to differentiate between add and edit functionalities. Hello, I am looking to edit in angular8 by setting up a boolean variable isEdit for distinguishing between adding and editing. Greetings! Currently work ...

Ways to navigate to a routerlink in Angular 2 without passing any parameters

Struggling with accessing a routerlink in Angular 2 without its parameters. The goal is to use the routerlinks to determine whether or not to display a specific element in the navigation. For normal routerlinks without parameters, I do it like this: *ngIf ...

Troubleshooting Issue with Angular 5: Inability to Hide Elements for Non-Authenticated Users

Below is the code from app.component.html <nav class='navbar navbar-default'> <div class='container-fluid'> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-targ ...

How to build a login page with a static header and footer using Angular2

For my latest project, I am currently in the process of developing an application using Angular2 and eclipse Neon. Utilizing angular-cli for this app, I am now focused on creating the login page. Within the app.component.html file, you will find the follow ...

Filtering database results from an Angular component

I am currently working on an Angular component and I have a result variable in the .ts file that stores data retrieved from the database. My goal is to filter this result variable to display only 20 records and sort them by date either in ascending or de ...

invoking an API within a map function and utilizing the response

vm.owners = parents.children.map(function(e) { getparentById(e.Id) .then(function(getresponse) { var parentLink = '<a href="/#/parent/onboard/' + e.Id + '" target="_blank">' + e.Number + "-&qu ...

Encountering a NativeScript error while attempting to set up and execute the android platform

When I try to run the command "tns build android", I encounter the following issue: The task ':asbg:generateInterfaceNamesList' failed to execute. An error occurred: Could not retrieve property 'jarFiles' for project ':asbg&apo ...

Eliminate the "Potential 'undefined' Object" error without resorting to non-null assertion or optional chaining

Below is the code snippet I am working with: export type ConditionalItemType = [ { condition: string }, { [key: string]: FormItemDataType } ]; export type ConditionalItemDataType = ConditionalItemType[]; export type FormItemDataType = { required: bo ...

What is the best way to send props to a child component in JSX with TypeScript?

While passing props to the child, I encountered an error message stating "Property 'isClicked' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes". I defined "isClicked?: boolean" in my code. What additional steps sho ...

Step-by-step guide on integrating jQuery-ui with Asp Core+ Angular 4 template using Visual Studio 2017

Using the Asp Core+webpack+ Angular 4 template from VS 2017, I am trying to figure out how to load jQuery-ui. I attempted to put it in webpack.config.vendor.js: const treeShakableModules = [ '@angular/animations', '@angular/common&a ...

Creating an Ionic 3 canvas using a provider

I recently followed a tutorial on integrating the canvas API into Ionic, which can be found at this link. However, I encountered an issue where all the canvas-related functions had to be placed within the pages class, making it quite cumbersome as these f ...

What causes an error when the App is enclosed within a Provider component?

What is causing the error when wrapping the App in Provider? Are there any additional changes or additions needed? Error: "could not find react-redux context value; please ensure the component is wrapped in a @Provider@" import React from ' ...

XState: linking together multiple promises seamlessly without needing intermediate states

After reading the Invoking Multiple Services section, it seems that despite being able to invoke multiple promises, they appear to be triggered without waiting for the previous one to complete in my own tests. // ... invoke: [ { id: 'service1' ...

What is the reason for the HTTP service being activated automatically?

Utilizing the Http service, data is fetched and then passed into the cached service. The component subscribes to the cached service and initiates the HTTP request. The HTTP GET service is intended to be called when the user clicks on an anchor tag. Upon c ...

Troubleshooting issue: matTooltip malfunctioning in *ngFor loop after invoking Angular's change

The matTooltip in the component below is rendering correctly. The overlay and small bubble for the tooltip are rendered, but the text is missing (even though it's present in the HTML when inspecting in the browser) and it isn't positioned correct ...

Using CamanJs in conjunction with Angular 6

Struggling to integrate camanjs with Angular 6? Wondering how to add the JavaScript library and use it within an Angular project when there are no types available on npm? Here are the steps I followed: First, install Caman using npm. Next, add it to ...

Methods to close the currently active ngx-modal when a new modal is triggered within the same Angular 8 component

I am currently working on developing a versatile modal component that has the ability to be called from within the same modal itself. Is there any way to configure the component and modal in such a manner that when the reusable component is triggered, it ...

The 'path' property is not found on the 'ValidationError' type when using express-validator version 7.0.1

When utilizing express-validator 7.0.1, I encounter an issue trying to access the path field. The error message indicates that "Property 'path' does not exist on type 'ValidationError'.: import express, { Request, Response } from " ...