What are the best practices for implementing MapLabel in an Angular project?

I need help displaying text on top of multiple polygons on a map. I've heard that Map Label can help with this, but I'm having trouble implementing it and can't find any NPM resources.

Here is the Stack Blitz URL for reference: https://stackblitz.com/edit/angular-draw-polygon-google-maps-d4xnxq?file=app%2Fapp.component.ts

Your assistance with this issue would be greatly appreciated.

Thank you in advance.

Answer №1

The documentation for the Google Maps JavaScript API v3 Utilities mentions that MapLabel is included in packages that have not been officially published and are not actively maintained. If you want to prioritize its inclusion, you can open an issue on the GitHub link provided.

An alternative solution is to use a Marker object with an invisible image as an icon and then utilize the label property to display the desired label within your polygon. This gives the appearance of the label belonging to the polygon itself.

Below is a code snippet demonstrating this workaround, along with some sample code modified for the drawPolygon function. The image used ("https://ibb.co/cJpsnpb") serves as an invisible marker:

  drawPolygon() {
    const lat_lng = { lat: 66.7225378417214, lng: -155.04016191014387 };
    const map = new google.maps.Map(
      document.getElementById('map') as HTMLElement,
      {
        center: lat_lng,
        zoom: 7,
        mapTypeControl: true,
        mapTypeControlOptions: {
          mapTypeIds: ['roadmap'],
        },
      }
    );
    var infowindow = new google.maps.InfoWindow();
    this.mapIcons.data.forEach((poly, i) => {
      let polygonsMap = new google.maps.Polygon({
        map: map,
        paths: poly.polygons,
        strokeColor: '#FF8C00',
        fillColor: '#FF8C00',
        strokeOpacity: 0.8,
        strokeWeight: 2,
      });
      google.maps.event.addListener(polygonsMap, 'click', function (event) {
        infowindow.setContent(poly.locator);
        infowindow.setPosition(event.latLng);
        infowindow.open(map);
      });
      polygonsMap.setMap(map);
       var bounds = new google.maps.LatLngBounds();
       for (let i = 0; i < poly.polygons.length; i++) {
       bounds.extend(poly.polygons[i]);
     }
      var myLatlng = bounds.getCenter();

      const image =
      "https://ibb.co/cJpsnpb";
    const beachMarker = new google.maps.Marker({
      position: myLatlng,
      label: {
        text: poly.name,
        color: 'black',
        fontSize: "48px"
      },
      map,
      icon: image,
    });


      
    });
  }

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

When I try to integrate Three.js into my React application, it mysteriously causes my root HTML element

While attempting to utilize Three.js in Typescript react, I successfully rendered a Dodecahedron figure along with random stars. However, my intention was to incorporate some markup into my Three.js scene using React. Unfortunately, when I render the Three ...

Is it feasible to obtain the userId or userInfo from the Firebase authentication API without requiring a login?

Is it feasible to retrieve the user id from Firebase authentication API "email/password method" without logging in? Imagine a function that takes an email as a parameter and returns the firebase userId. getId(email){ //this is just an example return t ...

What is the process of creating a for loop in FindById and then sending a response with Mongoose?

Is there a way to get all the data in one go after the for loop is completed and store it in the database? The code currently receives user object id values through req.body. If the server receives 3 id values, it should respond with 3 sets of data to th ...

Function that sets object properties based on specified keys and verifies the value

Let's consider a scenario where we have an object structured like this: interface Test{ a: number; b: string; c: boolean; } const obj:Test = { a: 1, b: '1', c: true, } We aim to create a function that can modify the value ...

Is node.js necessary for running TypeScript?

Node.js is necessary for installing TypeScript. I believe that TypeScript utilizes Node.js to compile .ts files into .js files. My concern is whether the generated .js file needs node.js in order to function properly. From what I've observed, it seem ...

Angular time-based polling with conditions

My current situation involves polling a rest API every 1 second to get a result: interval(1000) .pipe( startWith(0), switchMap(() => this.itemService.getItems(shopId)) ) .subscribe(response => { console.log(r ...

The enum cannot be assigned a type of 'string | null'

Within my ProductGender enum, I have: enum ProductGender { Men, Women, } In my getProducts service: public getProducts( gender: ProductGender, category: ProductCategory ): Observable<IProductInterface[]> { return this.httpPro ...

Angular Error: Control not located at path 'instructions -> 1 ->action'

I am attempting to construct a form with the following structure. Users should have the ability to create multiple entries for the instruction fields. ... this.buttonForm = this.fb.group({ instructions: this.fb.array([ this.fb.group({ ...

Should the checkbox be marked, set to 1?

I am looking for a way to call a method when the user checks or unchecks multiple checkboxes. Do you have any suggestions on how I can achieve this? Here is what I have tried so far: <input type="checkbox" [ngModel]="checked == 1 ? true : checked == 0 ...

Error: The URL constructor is unable to process /account as a valid URL address

Working on a new social media app using appwrite and nextjs, encountering an error "TypeError: URL constructor: /account is not a valid URL" upon loading the website. Here's the current file structure of my app: File Structure Below is the layout.tsx ...

How to automatically disable a button in reactjs when the input field is blank

I have a component called Dynamic Form that includes input fields. The challenge I am facing is how to disable the submit button when these input fields are empty, although the validateResult function fails to return false. import cn from "classname ...

Issue with Ion-Searchbar visibility on Android device

My Angular (Ionic) app runs smoothly on the browser with no issues, using Angular v17.0.2 and Ionic v8.2.2. However, when I use npx cap sync and test it on a device with Android Studio, the layout looks distorted as shown in the second image I attached. I ...

The child component is receiving undefined props, yet the console.log is displaying the actual values of the props

Struggling to implement a Carousel in my Gatsby-based app, I encountered an issue with passing props from the Parent to Child functional component. The error message "TypeError: props.slide is undefined" was displayed, but upon checking the console logs, i ...

After the transition from Angular 8 to Angular 9, an issue arose with the node_modules/@zerohouse/router-tab/zerohouse-router-tab.d.ts file, as it was not declared

Error Image package.json { "name": "client", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "serveapp": "ng serve ...

What is the best way to trigger a click event on an input field inside a mat-form-field

I need to reset the selected option when clicking on the autocomplete button: <mat-form-field class="example-full-width" (click)="clear()" appearance="outline"> <input matInput placeholder="State" aria-label="State" [matAutocomplete]=" ...

RTK Query - executing a query upon mounting with lazy loading enabled

Should rerendering be triggered by sending a request on mount? Or is the use of useEffect necessary? (Is lazy mode different from regular queries?) export const Catalog: React.FC<CatalogProps> = ({ object, category }) => { const [getCatalogPro ...

Guide to navigating to a specific module within an Angular 2 application directly from the index page

As a newcomer to angular2, I recently obtained a sample login and registration code online. However, when I run the code, it displays the index page instead of the "login" module located within the app folder. Can someone please advise me on how to redire ...

Struggling to assign the correct data type to a property in Typescript

I am encountering a TypeScript error with the following code. In this interface, the 'items' property can be either an object or an array depending on the code and response. I am unsure how to specify the datatype of 'array/object/any', ...

The 'innerHTML' property is not present in the 'EventTarget' type

Currently, I am working with React and Typescript. My goal is to store an address in the localStorage whenever a user clicks on any of the available addresses displayed as text within p elements. <div className="lookup-result-container& ...

Tips for utilizing the forEach method in Angular 2 without relying on ngFor?

I recently started learning Angular 2 and I am trying to figure out how to access array details using a forEach loop and apply certain conditions on it. Once I make the necessary changes, I want to display this data using ngFor. In Angular 1, this was ea ...