What is the best way to include text or a label on my Angular map without using a marker?

I am currently using the agm-map module in my angular project. I want to place a label or text at the center of a polygon on the map without using markers. How can I achieve this functionality in Typescript?

I attempted to use the MapLabel Utility for this purpose. Here is the code snippet where I tried to implement it:

label: new MapLabel({
    text: result[index].name,
    position: new google.maps.LatLng(object.lat, object.lng),
    fontSize: 10,
    fontColor: #000,
    labelInBackground: true,
    strokeColor: #000,
    map: map
})

I also found a helpful resource at the following link: https://codepen.io/adg29/pen/reGaPd

Thank you in advance for your assistance.

Answer №1

Start by obtaining the coordinates of the polygon's center and utilize it as the label coordinates value. I acquired the polygon's center following guidance from a solution in this Stack Overflow post and utilized those coordinates for the ll parameter in the labelOverlay.

Here's the breakdown: Initially, note that you created the labelOverlay before the polygon. To determine the polygon's center, rearrange the order so the polygon precedes the labelOverlay.

Next, incorporate the code snippet from the Stack Overflow post to pass each polygon point to a LatLngBounds object using the extend() method.

Calculate the bounds' center and assign it as the ll value in your labelOverlay.

The provided code snippet demonstrates how the implementation should appear. A functional example can be viewed in this live fiddle.

 // Define the LatLng coordinates for the polygon's path.
  var triangleCoords = [
    {lat: 25.774, lng: -80.190},
    {lat: 18.466, lng: -66.118},
    {lat: 32.321, lng: -64.757},
    {lat: 25.774, lng: -80.190}
  ];

  // Construct the polygon.
  var bermudaTriangle = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });
  bermudaTriangle.setMap(map);
  var bounds = new google.maps.LatLngBounds();
  for (i = 0; i < triangleCoords.length; i++) {
  bounds.extend(triangleCoords[i]);
}

var polygonCenter = bounds.getCenter();

var overlay1 = new LabelOverlay({
    ll      : polygonCenter,
    //minBox    : box,

    minBoxH     : 0.346,
    minBoxW     : 1.121,

    maxBoxH     : 0.09,
    maxBoxW     : 0.3,

    //className : 'small',

    debugBoxes  : true,
    debugVisibility : true,

    maxZoom     : 10,
    minZoom     : 6,
    label       : "Hello world",
    map     : map
});

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

Breaking down an object using symbols as keys in Typescript

I'm encountering an error when running this code Type 'symbol' cannot be used to index type '{ [x: string]: string; }'.: let symbol = Symbol() let obj = { [symbol] : 'value'} let { [symbol]: alias } = obj // ...

Converting Angular 5 select option values to strings is a must

I have set up a basic select connected to a variable like this: <select id="client" name="client" [(ngModel)]="order.clientId"> <option *ngFor="let client of clients" [value]="client.id"> {{ client.name }} </option> </ ...

Issues with the functionality of Angular Firebase Authentication Service

I am currently working on setting up an authentication service in Angular that will integrate with Google Firebase for a Login form. However, I have encountered an issue where including the service in the constructor of my LoginComponent prevents me from a ...

Struggling to retrieve service information for implementation in the component

I am currently working on a project where: 1. I have created a news.service.ts service file with the following code: 2. Within the service, I have implemented a function named throwData() that returns the service data. Here is the code snippet: im ...

Angular service is able to return an Observable after using the .then method

I am currently facing an issue with retrieving the authentication status in a service method. Everything seems to be working fine except for the return statement. I am struggling with the usage of .then inside .map and I am unable to figure out how to retu ...

Encountering difficulty with retrieving information from a shared service on Angular 6

Attempting to pass JSON data from one component to another component (like parent to child) using a service. The service has two methods: setJsonData and getJsonData. Service Class import { Injectable } from '@angular/core'; @Injectable({ pr ...

Tips for dynamically implementing a pipe in Angular 5

In my Angular application, I have implemented a filter using a pipe to search for option values based on user input. This filter is applied at the field level within a dynamically generated form constructed using an ngFor loop and populated with data from ...

Closing ngx-bootstrap modal post unit tests

After enabling the CSS style in the unit tests of my Angular app, I noticed that every time a component displaying a modal from ngx-bootstrap appears, it remains visible in the browser even after the unit tests for that component have completed running. T ...

Leveraging File functionality in TypeScript

In the process of developing a web application with Angular 4 and Typescript, I encountered an issue while attempting to retrieve the date of a file for upload. Specifically, when trying to access the lastModified property of a File object, Typescript retu ...

Unable to retrieve a property from a variable with various data types

In my implementation, I have created a versatile type that can be either of another type or an interface, allowing me to utilize it in functions. type Value = string | number interface IUser { name: string, id: string } export type IGlobalUser = Value | IU ...

What is the proper way to incorporate the "pdf" package into a TypeScript project?

I recently installed pdf and its types using the following command: npm install --save pdf @types/pdf However, I am struggling to find any documentation on how to actually use this package. When I try the following code: import {PDFJS} from 'pdf&ap ...

Steps to Transform String Array into Prisma Query Select Statement

I have a requirement to dynamically select Prisma columns based on client input: ['id', 'createdAt', 'updatedAt', 'Order.id', 'Order.Item.id', 'Order.Item.desc'] The desired format for selection ...

How do you go about making a prop optional in Typescript based on a generic type?

In my app, I have a specific type with optional props based on a generic type: type MyCustomType<R extends Record<string, string> | undefined, A extends string[] | undefined> = { record: R, array: A } There is a function that directly uses ...

Exploring the Latest Features: Using Angular 7 with Bootstrap Collapse for Dynamic Aria-Controls

I am currently working on creating my own component to use within an *ngFor loop. I am facing an issue where I need a unique value for my Collapse feature. Right now, when I click on the second main row in the table, the collapse feature only shows the inn ...

Unsubscribing from a nested observable - a step-by-step

In our Angular component, we leverage the ngOnDestroy() method to handle canceling http requests that are still pending when navigating away from a page. To avoid reloading data that has already been fetched, we utilize a custom generic cache helper on cer ...

The service remains operational while the button's status undergoes a change

In my data table, each row has a column containing buttons. To ensure that only the button in the clicked row is executed, I include the index of that row in the start/pause timer function. I decided to create these functions in a service so that the time ...

The issue with Angular 2's Parameterised router link component not fully refreshing

I'm trying to figure out how to show a set of images when I click on a specific menu item. The menu structure looks like this: <ul id="demo23" class="collapse"> <li> <a [routerLink]="['image-gallery','Picasso ...

The module '@angular/http/src/static_response' or its corresponding type declarations could not be located

I'm encountering an issue in my Angular v12 project where I receive the error message Cannot find module '@angular/http/src/static_response' or its corresponding type declarations when I attempt to use the import statement in my code: import ...

Tips for deleting a user from the UI prior to making changes to the database

Is there a way to remove a participant from the client side before updating the actual state when the submit button is clicked? Currently, I am working with react-hook-form and TanstackQuery. My process involves fetching data using Tanstack query, display ...

You cannot directly access an array useState by index in React js, but you can use the map function to

export interface JobListing { id: number, isTraded: boolean, feedback: string, title: string, message: string, skills: string[], sender: string, ipAddress: string } const GroupList = () => { const [jobListings, setJobListings] = useSt ...