400 error trying to loadGeoJson in Angular Google Maps project

309 views Asked by At

I am getting a 400 error when trying to loadGeoJson into my map. The file is located in my src/assets folder. If I put a different file in that folder, I can access it with a http request when I start the ng server, so that means I should have access to those files. But for the file that I specify in my loadGeoJson method call, if I try to display it in the browser with http://localhost:4200/assets/sample-farms.geojson the browser displays the home screen of my application...

So there is some weird redirect going on?

Here is my code:

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);
  });

  }
}

This is the error that I get in the console:

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

Any help much appreciated.

1

There are 1 answers

3
chrismclarke On BEST ANSWER

You should try put that url in your address bar first to check the file does exist. If so then I'm guessing it's an issue with how the maps API imports data (API for ref: https://developers.google.com/maps/documentation/javascript/reference/data#Data.loadGeoJson)

I would suggest importing the file using angular's own HTTP client - https://angular.io/guide/http (or any other preferred client), and then passing that data directly via the addGeoJson() method instead.