0

我想根据输入框中输入的坐标在谷歌地图中绘制一个多边形。

在输入框中输入坐标集后,单击绘制多边形按钮后,我想在谷歌地图(agm 地图)中绘制一个多边形。

请帮忙。

4

1 回答 1

1

在我回答您的问题之前,您应该注意的一件事是 Stack Overflow 不是免费的代码编写服务。您应该尝试自己编写代码。在进行更多研究后,如果您遇到问题,您可以发布您尝试过的内容,并清楚地解释什么不起作用并提供最小、完整和可验证的示例。我建议阅读如何提出一个好的问题和完美的问题一。另外,请务必参加游览阅读

话虽如此,您实际上可以在 Angular 上本地实现 Google Maps API,而不是依赖 3rd 方库 (AGM)。这样,您只需在初始化 Maps JS API 后按照官方文档进行操作即可。这应该会让您省去很多麻烦,而不是遵循不可预测的3rd 方文档

这是满足您要求的示例代码:https ://stackblitz.com/edit/angular-draw-polygon

你也可以只看下面的代码:

索引.html

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

地图组件.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>

地图组件.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);
  }
}

样式.css

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

.map {
  height:100%;
}
于 2020-10-01T07:52:58.873 回答