How to generate a polygon shape with Angular 2 using the agm library

I'm working on generating a polygon using the AGM library in Angular 2. Here's the template I am using:

<div id="google_map" [@cardtable2]>
            <sebm-google-map #maps [latitude]="latitude" [longitude]="longitude" [scrollwheel]="false" [zoom]="zoom">

                <sebm-google-map-marker 
                    *ngFor="let m of markers; let i = index"
                    (markerClick)="clickedMarker(m.label, i)"
                    [latitude]="m.lat"
                    [longitude]="m.lng"
                    [label]="m.label"
                    [markerDraggable]="true"
                    (dragEnd)="markerDragEnd(m, $event)">

                    <sebm-google-map-info-window>
                    <strong>{{m.label}}</strong>
                    </sebm-google-map-info-window>          
                </sebm-google-map-marker>
            </sebm-google-map>
        </div>

In the controller, I attach the polygon like this:

var city_bounds = [ 
   // coordinates for the polygon vertices
    ]


this.mapsAPILoader.load().then(() => {
  this.path = city_bounds.map(point => {
    return new google.maps.LatLng(point.latitude, point.longitude);
  });

  let city_bounds_polygon = new google.maps.Polygon({
    paths: this.path,
    editable: false,
    draggable: false
  })

  city_bounds_polygon.setMap(this.mapsElementRef);
}); 

Upon starting the node server, I encounter the following error:

Error TS2345: Argument of type 'ElementRef' is not assignable to parameter of type 'Map'.
  Property 'fitBounds' is missing in type 'ElementRef'.

The issue seems to be with the map reference. In plain JavaScript, we can easily create maps using new google.maps.Maps, but since the map is created using an Angular directive sebm-google-map, I obtained its reference using ViewChild. However, when trying to use it with setMap, I get the above error.

I believe I need to utilize AgmPolygon from the AGM library, but I'm unsure about how to implement it since there are no examples provided in the documentation. Can anyone guide me on how to correctly use the AGM library to create a Polygon?

The version of AGM being used is 0.16.0, which was previously known as angular2-google-maps/core.

Answer №1

I have successfully resolved the issue with agm +2:

 handleMapClick(data){

    this.path.push({ lat: data.coords.lat, lng: data.coords.lng });

    let updatedArray = Array<any>();
    this.path.forEach((item) => {
      updatedArray.push(item);
    });
    
    this.path = updatedArray;

   } 

// end of map click handling function

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

The data is not being displayed in the table

I am encountering an issue while attempting to populate the table with data received through props by looping over it. Unfortunately, the data is not rendering on the UI :( However, when I manually input data, it does show up. Below is my code: Code for P ...

Is it possible in JavaScript to pass undeclared method parameters without using eval()?

Understanding from just the title can be tricky. Let me provide an example. I need a function to automatically refer to a variable that is "injected", like this: function abc() { console.log(myVariable); } I attempted to achieve this with: with({myVa ...

Using JavaScript variables in CSS: a beginner's guide

My website features a typewriter effect, but I want the animation to match the length of the words exactly. I attempted using JavaScript variables in CSS, but unfortunately, it's not functioning properly. Could someone please advise me on how to remed ...

Modify the background color when hovering using jquery

In order to have buttons with variable colors and a different hover color, I have to apply inline CSS. Since the hover color cannot be added using inline CSS, I need to use JavaScript. I attempted to achieve this using the .hover() function, but the colors ...

Issue arises when attempting to transfer data collection object from Jquery ajax Method to MVC Controller resulting in null object being displayed

I am attempting to pass a data object to an MVC controller using a jQuery method. When I click the submit button, a data object is created in a JavaScript method. The data object is not null in the Ajax method. However, when I try to pass it to the MVC con ...

Assign the colId to the pinnedBottomRowData property within Ag Grid

I'm facing an issue with displaying data in the pinned row within ag-Grid Vue 2. I am utilizing pinnedBottomRowData to supply data for the pinned row, but despite the pinned row being visible, it remains empty. The problem arises from using dot notati ...

Most effective method for showcasing the image once it has been successfully loaded

At the moment, I am considering two methods to display an image after it has been loaded. Initial Method <img id="myImage" /> var img = new Image(), x = document.getElementById("myImage"); img.onload = function() { x.src = img.src; }; img ...

What is the process for combining two distinct geometries with different materials into a single entity in three.js?

I created a 2D square line diagram followed by another square diagram with a sample image in the center position. However, one of them is visible while the other is hidden. I used two different geometries and materials - one with a line-based material se ...

Using jQuery and Flask-WTF to achieve live word count in a TextAreaField - a step-by-step guide!

I am interested in adding a real-time word count feature to a TextAreaField using jQuery. I found an example that I plan to use as the basis for my code: <html lang="en"> <head> <script src= "https://code.jquery.com/jquery ...

Interacting between Angular controllers and directives while maintaining separation of concerns

In my AngularJS project, I've implemented a directive within a module named ThreeViewer that displays WebGL scenes based on the specified source file. The code snippet below outlines the basic functionality: angular.module('ThreeViewer', [] ...

Switching the input of data from a string format to a date format

One of the components in my registration form requires the user to input their start date. I am currently utilizing a MEAN Framework, specifically AngularJs for the front end development. Progress so far: Initially, I attempted using the code snippet bel ...

Creating a link button using JavaScript

I have integrated a Setmore code on my website to facilitate appointment booking, which triggers a popup similar to what you would see on a hotel reservation site. <script id="setmore_script" type="text/javascript" src="https://my.setmore.com/js/iframe ...

What is the best way to compare two arrays in my JSON data?

Hello, I'm trying to compare two arrays - one from my JSON data and the second from a regular array. Specifically, I want to check if the ids of "cm:taggable" exist in my secondArray. JSON { "entry": { "isFile": true, "createdByUs ...

Creating elements with looping can be accomplished by using a combination of

Looking for assistance on looping through data displayed in a div tag using the code below: function GetDataFromServer() { var url = "http://bertho.web.id/curl/services21/DataReadNP.php"; JSONP.get(url, {}, function(response){ var listItem, container ...

Updating the root URL in PhoneGap: A step-by-step guide

Is there a way to change the root URL of my application so that it loads my.com domain when it starts? I've tried changing the line below in config.xml but it doesn't seem to have any effect: <content src="index.html"/> ...

Failure to load content into element with .load function

My code looks like this: $(function () { $('#result').load('_shared.html body > :not(main)'); }); However, the <div id="result" /> element remains empty. When I try the same selector in the console on _shared.html: $(&a ...

Field must have a base type specified to proceed

Currently, I am in the process of developing a discord.js bot. The structure I have set up involves a folder that contains all the commands, and when a command is called, index.js directs it to the appropriate file. However, when attempting to run the bot, ...

Text centered vertically with jQuery is only loaded after the page is resized

My jQuery script is designed to vertically center text next to an image, but it seems to only work properly after resizing the page. $(window).load(function () { $(function () { var adjustHeight = function () { $('.vertical-al ...

Request with content Type multipart/form experienced Error 406

I encountered an issue with my axios request in Express const formData = new FormData(); formData.append("file", fs.createReadStream(file.path)); formData.append("requestid", '123456'); const options = { method: 'POST& ...

How can I append a hash to a URL using JavaScript without causing the page to scroll?

Is it possible to add a hash to the URL without scrolling the page using JavaScript? I navigate to the page I scroll down I click on a link that adds a hash (for example: http://www.example.com/#test) The page should not scroll back to the top. What is ...