尝试在 Angular Google 地图项目中加载 GeoJson 时出现 400 错误

400 error trying to loadGeoJson in Angular Google Maps project

我在尝试将 GeoJson 加载到我的地图时收到 400 错误。 该文件位于我的 src/assets 文件夹中。 如果我在那个文件夹中放了一个不同的文件,我可以在启动 ng 服务器时通过 http 请求访问它,这意味着我应该可以访问这些文件。 但是对于我在 loadGeoJson 方法调用中指定的文件,如果我尝试在浏览器中显示它 http://localhost:4200/assets/sample-farms.geojson 浏览器显示我的应用程序的主屏幕...

所以发生了一些奇怪的重定向?

这是我的代码:

import { analyzeAndValidateNgModules } from '@angular/compiler';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
})
export class AppComponent {
  title = 'simple-gmaps-demo';

  map: any; // important to declare the type of property map, so we can refer to it with this.map
  features: any;  // Do I need this too?
  

  onMapReady(map: google.maps.Map) {

    this.map = map;
    this.map.setCenter({lat:-32.910, lng:117.133});
    this.map.setZoom(10); 

    // Error in this method call?
    this.map.data.loadGeoJson('http://localhost:4200/assets/sample-farms.geojson', {}, 
    function (features: any) {
    console.log(features);
  });

  }
}

这是我在控制台中得到的错误:

zone-evergreen.js:2845 GET http://localhost:4200/assets/sample-farms.geojson 404 (Not Found)

非常感谢任何帮助。

您应该先尝试将 url 放入您的地址栏,以检查该文件是否存在。如果是这样,那么我猜这是地图 API 如何导入数据的问题(API for ref: https://developers.google.com/maps/documentation/javascript/reference/data#Data.loadGeoJson

我建议使用 angular 自己的 HTTP 客户端 - https://angular.io/guide/http(或任何其他首选客户端)导入文件,然后通过 addGeoJson() 方法直接传递该数据相反。