How do I draw polygon in agm map based on Input co-ordinates in Angular?

2.2k views Asked by At

I want to draw a polygon in the Google maps based on the co-ordinates input in the input box.

After entering the set of co-ordinates in the input box, once I click on Draw polygon button, I would like to draw a polygon in the Google map(agm map).

1

There are 1 answers

1
Ricky Cuarez On

Instead of relying on a 3rd party library (AGM), you can actually just implement Google Maps API natively on Angular. This way, you can just follow the official documentation once you initialize Maps JS API. This should save you a lot of headache instead of following unpredictable 3rd party documentations.

Here is a sample code with your requirements: https://stackblitz.com/edit/angular-draw-polygon

You can also just see the code below:

index.html

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
<my-app>loading</my-app>

mapComponent.html

longitude: <input placeholder="longitute" name="longitute" [(ngModel)]="longitute" required >
<h2>Coordinates:</h2>
<ul>
    <li *ngFor="let coordinate of coordinates">
      {{ coordinate.lat }},{{coordinate.lng}}
    </li>
  </ul>
<button type="submit" (click)="onAdd()">Add coordinates</button>
<button type="submit" (click)="onSubmit()">Draw Polygons</button>
<div #map class="map"></div>

mapComponent.ts

import { Component, OnInit, ViewChild } from "@angular/core";
declare const google: any;

@Component({
  selector: "my-maps",
  templateUrl: "./simple-map.component.html",
  styleUrls: ["./simple-map.component.css"]
})
export class MapComponent implements OnInit {
  @ViewChild("map", { static: true }) mapElement: any;
  map: any;
  latitude: number;
  longitute: number;
  coordinates = [];

  constructor() {}

  ngOnInit() {
    const mapProperties = {
      center: new google.maps.LatLng(-33.8569, 151.2152),
      zoom: 11,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    this.map = new google.maps.Map(
      this.mapElement.nativeElement,
      mapProperties
    );
  }

  onAdd() {
    var stringToJson = JSON.parse(
      '{"lat":' + this.latitude + "," + '"lng":' + this.longitute + "}"
    );
    this.coordinates.push(stringToJson);
    this.latitude = null;
    this.longitute = null;
  }

  onSubmit() {
    const polygon = new google.maps.Polygon({
      paths: this.coordinates,
      strokeColor: "#FF0000",
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: "#FF0000",
      fillOpacity: 0.35
    });
    polygon.setMap(this.map);

    // Create the bounds object
    var bounds = new google.maps.LatLngBounds();

    // Get paths from polygon and set event listeners for each path separately
    polygon.getPath().forEach(function(path, index) {
      bounds.extend(path);
    });
    console.log(bounds);

    // Fit Polygon path bounds
    this.map.fitBounds(bounds);
  }
}

style.css

  height: 100%;
  margin: 0;
  padding: 0;
}

.map {
  height:100%;
}