finding a location on google map with a postcode in Angular 5

Issue

I’m going to use google map to find a location with a postcode in Angular 5.
How can I do that?

Solution

we can combine Geocoding Service and Angular Google Maps (AGM) to achieve our requirement.

Here is a quick sample you can refer to for a quick glance.

Stackblitz Here

just an interface for type safety.

interface marker {
    lat: number;
    lng: number;
}

And app component :

export class AppComponent  {
  // google maps zoom level
  zoom: number = 14;

  // initial center position for the map
  lat: number = 31.5464762;
  lng: number =  120.2796121;

  code:number;
  address:string;
  center:marker;
  polygon:marker[];

  constructor(private http: Http){

  }

  clickedMarker(label: string, index: number) {
    console.log(`clicked the marker: ${label || index}`)
  }


  markerDragEnd(m: marker, $event: MouseEvent) {
    console.log('dragEnd', m, $event);
  }

  searchCode(){
    this.CallGeoAPI().subscribe(res=>{
      console.log(res);
      const result = res[0];
      this.address = result.formatted_address;
      this.center = result.geometry.location;
      this.lat = this.center.lat;
      this.lng = this.center.lng;
      this.polygon = [
        {
          lat: result.geometry.bounds.northeast.lat,
          lng: result.geometry.bounds.northeast.lng
        },
        {
          lat: result.geometry.bounds.northeast.lat,
          lng: result.geometry.bounds.southwest.lng
        },
        {
          lat: result.geometry.bounds.southwest.lat,
          lng: result.geometry.bounds.southwest.lng
        },
        {
          lat: result.geometry.bounds.southwest.lat,
          lng: result.geometry.bounds.northeast.lng
        },
      ]
    })

  }
  CallGeoAPI(){
    let apiURL = `https://maps.googleapis.com/maps/api/geocode/json?address=${this.code}&key=AIzaSyAgDUII_kvGfCJNmu4qhhzjl8YNzblV9Ng`;
    return this.http.get(apiURL).map((response: Response)=>{
      return response.json().results;
    })
  }

}

Answered By – AbolfazlR

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.