angular-google-maps icon indicating copy to clipboard operation
angular-google-maps copied to clipboard

agm-polygon not working properly with *ngFor, InvalidValueError: not an Array

Open dikey94 opened this issue 8 years ago • 17 comments

Issue description Hi guys, I have a little problem with moving paths into a separated model. Let's say I have a collection of restaurant. Each restaurant has a collection of delivery zones, each delivery zone has separated paths.

After changing [paths]="paths" into [paths]="zone.paths" I get

InvalidValueError: not an Array

My code is pretty simple:

<agm-map [latitude]="restaurant.latitude" [longitude]="restaurant.longitude">
  <agm-marker [latitude]="restaurant.latitude" [longitude]="restaurant.longitude"></agm-marker>
  <agm-polygon *ngFor="let zone of restaurant.delivery_zones" [fillColor]="red"
               [fillOpacity]="0.5" [paths]="zone.paths"
               [strokeColor]="blue" [strokeOpacity]="0.6" [strokeWeight]="2"
               [visible]="true" [zIndex]="1"></agm-polygon>
</agm-map>

DeliveryZone model:

...
public paths = [
    {lat: 25.774, lng: -80.190},
    {lat: 18.466, lng: -66.118},
    {lat: 32.321, lng: -64.757}
  ];
...

I'm not an expert in Angular.

Thanks!

dikey94 avatar Jan 25 '18 17:01 dikey94

Try this @dikey94

<agm-map [latitude]="restaurant.latitude" [longitude]="restaurant.longitude">
  <agm-marker [latitude]="restaurant.latitude" [longitude]="restaurant.longitude"></agm-marker>
  <agm-polygon *ngFor="let zone of restaurant.delivery_zones" [fillColor]="red"
               [fillOpacity]="0.5" 
               [strokeColor]="blue" [strokeOpacity]="0.6" [strokeWeight]="2"
               [visible]="true" [zIndex]="1" >
 <ng-container *ngFor="let point of paths">
      <agm-polyline-point   [latitude]="point.lat" [longitude]="point.lng">
</agm-polyline-point>
</ng-container>Ï
</agm-polygon>
</agm-map>

nedpuganti avatar Feb 03 '18 14:02 nedpuganti

public paths = [
    {lat: 25.774, lng: -80.190},
    {lat: 18.466, lng: -66.118},
    {lat: 32.321, lng: -64.757}
  ];

That is not an array or an iterable, but an Object with a key/value pairing. Instead define your paths as an array so it can be indexed by ngFor.

Try something like this instead

private paths: Array<google.maps.LatLng> = [
    new google.maps.LatLng(25.774, -80.190),
    new google.maps.LatLng(18.466, -66.118),
    new google.maps.LatLng(32.321, -64.757)
  ];

timcblank avatar Feb 15 '18 22:02 timcblank

did you solver this @dikey94 ?

sebitoelcheater avatar Feb 26 '18 14:02 sebitoelcheater

I don't see how this can be an issue with AGM. If you can create a repro, I'll re-open it or tell you how to fix it. But ngFor is part of Angular, not AGM. If it complains, you're looking for the solution in the wrong place.

Unless, of course, we're using ngFor internally and we're passing in something wrong to it, which does not seem to be the case.

lazarljubenovic avatar Feb 26 '18 18:02 lazarljubenovic

I am having a similar issue, I see that shis issue is closed but no definite solution was highlighted.

Cromies avatar Jun 04 '18 14:06 Cromies

@Cromies Are you absolutely sure you're passing an instance of Array?

lazarljubenovic avatar Jun 04 '18 14:06 lazarljubenovic

I have to admit I didn't solve this issue. What I did is changed my maps implementation from agm into a clean js google maps code.

I know this is not a fix but, but... dead lines.

I'm following this topic.

Thanks.

dikey94 avatar Jun 04 '18 15:06 dikey94

@lazarljubenovic 100% sure

`
 public mkSquares(value: any){
        let squares: Array<LatLngLiteral> = [];
        let packet: Array<LatLngLiteral>;
        this.detection.getSections().subscribe(data => {
            console.log(data);
            for (let index in data){
                let obj = [];
                for (let point of value){

                    if(data[index]['SECTION_ID'] == point.SECTION_ID){
                        let coords = point.LAT_LON.split(",");

                         packet = {
                            lat: parseFloat(coords[0]),
                            lng: parseFloat(coords[1])
                        }
                        obj.push(packet);
                    }
                }

                squares.push(obj);

            }
            this.paths = squares;
            console.log(this.paths);
        })
    }

This function makes a multidimensional array out of the data being pulled from a database. In that array, each square contains { lat: , lng} coordinates. I run without error, yet nothing displays.

Cromies avatar Jun 04 '18 19:06 Cromies

By "nothing displays" I mean on the map. The values are produced, and rendered in my console when I run the console.log, yet the map does not show the paths

Cromies avatar Jun 04 '18 19:06 Cromies

When I remove the parseFloat() function away from the coords I get the

ERROR Error: Uncaught (in promise): InvalidValueError: at index 0: at index 0: not a LatLng or LatLngLiteral: in property lat: not a number

Error. So I know at the very least agm-polygon is recieving the paths that I'm sending.

Cromies avatar Jun 04 '18 19:06 Cromies

Ok, now this issue can be closed. When making your coordinates, make sure to use MapsAPILoader to gain full access to the google api. Then further use that functionality to properly create LatLngLiteral's

Cromies avatar Jun 04 '18 20:06 Cromies

Glad you got it working. Thanks for the tips, hope they are useful to others.

lazarljubenovic avatar Jun 04 '18 21:06 lazarljubenovic

@Cromies Can you be more specific? I'm new to agm, what should I do exactly to show polygons on the map with ngFor? Thank you!

tolvaly avatar Aug 14 '18 09:08 tolvaly

@Cromies, I just came across this and it sounds like we have the same issue. Im very new to angular and would like to see how you fixed this issue.

Lweaver5051 avatar Aug 30 '18 15:08 Lweaver5051

@tolvaly heres what the html snippet looks like for my map:

`          <agm-map  [latitude] = 'lat'  [longitude] = 'lon' [zoom]=16 [panControl] = "true" [zoomControl] = "true" [mapTypeControl]="true" [fullscreenControl]="true" [mapTypeId] = "'satellite'">
              <agm-polygon *ngFor='let path of paths'  [strokeColor]="'#083478'" [strokeWeight]="4" [paths]="path">
              </agm-polygon>
          </agm-map>
`

where 'paths' or 'this.paths' is produced by this function:

`		public mkSquares(value: any){
				let squares = [];
				this._loader.load().then(() => {
						this.detection.getSections().subscribe(data => {
								for (let index in data){
										let obj = [];
										for (let point of value){

												if(data[index]['SECTION_ID'] == point.SECTION_ID){
														let splits = point.LAT_LON.split(",");


														 let coords  = new google.maps.LatLng(parseFloat(splits[0]), parseFloat(splits[1]));
														obj.push(coords);
												}
										}

										squares.push(obj);

								}
								this.paths = squares;
						})

				})
		}
`

In which, I utilize 'this._loader.load()' where 'this._loader' is 'MapsAPILoader', defined in my constructor.

Later, for more detailed lines, I did the following to gain full access to the google maps api:

`		@ViewChild(AgmMap) agmMap;

		ngAfterViewInit(): void {
				this.agmMap.mapReady.subscribe(map => {
						console.log('native map', map);
                                }
              }

`

make sure to have 'declare var google: any;' at the top, along side your imports or you won't be able to use the google objects like google.maps.Marker, etc.

Hope this helps!

Cromies avatar Aug 30 '18 18:08 Cromies

I faced the same issue but was fixed after I mapped my data format from Array<LatLngLiteral> to Array<Array<LatLngLiteral>>

Working format

const paths: Array<Array<LatLng | LatLngLiteral>> = [
  [
    {
      "lat": 7.031,
      "lng": 125.573
    },
    {
      "lat": 7.031,
      "lng": 125.575
    }
  ]
];

Seems like the Array<LatLng | LatLngLiteral> format is not working.

package.json

{
  "dependencies": {
    "@agm/core": "^1.1.0",
    "@agm/drawing": "^1.1.0",
    "@angular/animations": "~9.1.11",
    "@angular/cdk": "^9.2.4",
    "@angular/common": "~9.1.11",
    "@angular/compiler": "~9.1.11",
    "@angular/core": "~9.1.11",
    "@angular/forms": "~9.1.11",
    "@angular/material": "^9.2.4",
    "@angular/platform-browser": "~9.1.11",
    "@angular/platform-browser-dynamic": "~9.1.11",
    "@angular/router": "~9.1.11",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  }
}

sarenodev avatar Jul 15 '20 10:07 sarenodev

My (polyPathsChange) was not detecting changes when I edited a polygon for the 2nd time.

The solution I found was to reset the list that will be loaded in agm-polygon, to force it to detect changes.

<agm-polygon *ngFor="let polygon of loadedPolygons"
....
[paths]="polygon.paths"
(polyPathsChange)="changePolygon(polygon.id, $event)">
</agm-polygon

Inside my save/edit polygons method I do the following action inside .subscribe:

const copy= [...this.loadedPolygons];
this.loadedPolygons = [];
this.loadedPolygons.length = 0;
setTimeout(() => this.loadedPolygons = copy, 10);

This way, Angular/AGM can detect the change and edit the polygon coordinates correctly from the 2nd edition onwards.

yagoromualdo avatar Nov 12 '24 20:11 yagoromualdo