Angular 5 requires the Google Map API call to be made before initiating the http get request

I am experimenting with URL parameters to make a GET request and then use JSON output to drive a query in Google Maps. Currently, I have managed to make the embedded map function by sanitizing it and passing static data. However, when making the query call, it stops after building the URL, resulting in 'undefined' as the outcome.

@Component({
  selector: 'app-contactdetail',
  templateUrl: './contactdetail.component.html',
  styleUrls: ['./contactdetail.component.css']
})
export class ContactdetailComponent implements OnInit {
  contactId: string;
  contactDetail: Object = { };
  lat: string;
  lng: string;
  queryBuilder = `&q=${this.lat},${this.lng}`;
  apiLink = `https://www.google.com/maps/embed/v1/place?key=`;
   // `&q=321+Fake+Street,Mouton+ME`
  apiKey = `lol`;
  builtLink = `${this.apiLink}${this.apiKey}${this.queryBuilder}`;
  url: string = this.builtLink;
  urlSafe: SafeResourceUrl = 
this.sanitizer.bypassSecurityTrustResourceUrl(this.url);;

  constructor(private route: ActivatedRoute,
              private http: Http,
              private sanitizer: DomSanitizer
             ) {}

  ngOnInit() {
    this.contactId = this.route.snapshot.params.id;
    this.getContactDetail(this.contactId);
    console.log(this.urlSafe);
    console.log(this.builtLink);
  }
  // TODO: make this pass in an option eventually.

  /*   buildQuery(){
    const address = `&q=${this.contactDetail.address.split(' 
').join('+')},`;
    const city = ``
  } */

  async buildURL(url) {
    const sanitized = 
this.sanitizer.bypassSecurityTrustResourceUrl(url);
    return sanitized;
  }

  async getContactDetail(contactId) {
    return this.http
      .request(`http://localhost:3000/contacts/${contactId}`)
      .subscribe((res: any) => {
        this.contactDetail = res.json();
        if (this.contactDetail.hasOwnProperty('geoLocation_lat')) {
          this.lat = this.contactDetail['geoLocation_lat'];
          console.log(this.lat);
        }
        if (this.contactDetail.hasOwnProperty('geoLocation_lng')) {
          this.lng = this.contactDetail['geoLocation_lng'];
          console.log(this.lng);
        }
        console.log(this.contactDetail);
      });
  }
}

And here is the HTML code that I am trying:

</div>
    <iframe
      width="600"
      height="450"
      frameborder="0"
      style="border:0"
      [src]="urlSafe">
    </iframe>
  </div>

As a beginner in Web Development, any help or guidance would be greatly appreciated. Thank you.

Answer №1

It's puzzling how the google maps query gets triggered, but as long as it happens correctly post .getContactDetails completion, it appears that the URL needs to be defined in the subscription. So,

queryBuilder = `&q=${this.lat},${this.lng}`;
apiLink = `https://www.google.com/maps/embed/v1/place?key=`;
// `&q=321+Fake+Street,Mouton+ME`
apiKey = `lol`;
builtLink = `${this.apiLink}${this.apiKey}${this.queryBuilder}`;

is static and relies on currently set values for .lat and .lng, which are not defined.

Swap .getContactDetail with

async getContactDetail(contactId) {
    // ...http request
    .subscribe(res => {
        // ...parse .lat and .lng; handle parsing errors
        this.queryBuilder = `&q=${this.lat},${this.lng}`;
        this.apiLink = `https://www.google.com/maps/embed/v1/place?key=`;
        this.builtLink = `${this.apiLink}${this.apiKey}${this.queryBuilder}`;
    });
}

Make sure to construct the URL accurately.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Custom error handlers are never triggered by Angular 2 errors

I'm facing an issue with my Angular custom error handler implementation (v2.4.3). Even though I have a simple setup, the errors are not being logged. What could be causing this problem? app.module.ts providers: [ { provide: ErrorHandler, useClas ...

``There seems to be an issue with the functionality of Passport.js' multiple login system

I'm encountering a strange issue with my login system. Everything seems to be working fine, including local login, Google login, and Facebook login. However, the problem arises when I attempt to register with Google after already registering with Face ...

Unable to adjust dimensions with CSS width and height properties

I'm currently working on developing an online game with a login screen inspired by Paper.io. I have created the username input and play button, but there seems to be an issue with the width and height specified in the CSS file for the input field. Eve ...

Master the Art of Animating Letters in the DOM by Navigating Through Any Array of Characters

I am attempting to implement a typewriter effect animation where a new message is displayed and animated as I type into an input box. Initially, I tried using a global char variable to iterate through each element of the array. However, whenever I passed ...

Angular implementation of the scroll down effect in bootstrap navigation

I have integrated a bootstrap template into my Angular web application, specifically using this template. If you visit the live preview, you will notice a scroll-down effect on the navigation bar. You can find the code for this navigation bar effect here: ...

What is the best way to implement a dynamic templateUrl for an Angular 2 Component?

My goal is to dynamically load a component's templateUrl based on a value passed from the parent component. I understand that this can be achieved by using property binding to pass the value through @Input. Below, I have provided an example where the ...

Use include files to wrap content in a div tag

I have a webpage index.html with the following JavaScript scripts: <script type="text/javascript> $(document).ready(function() { $('a.link').click(function() {var url = $(this).attr('href'); $('#content'). ...

Angular.js and D3 - The Perfect Combination for Dynamic Data Visualization!

Having some trouble creating a chart with angular.js. The chart is not appearing on the page when using rout.js, but it works fine without it. Here's my code: var myapp = angular.module('myapp', ['angularCharts']); function D3 ...

What is the best way to iterate through an array of images and upload them individually, ensuring that they do not have duplicate names

In my current code snippet, I am working with an array of images called images and uploading each image within that array. Everything seems to be working correctly, but I am encountering a minor issue where all the uploaded images end up having the same na ...

Troubleshooting a pair of distinct software programs: Angular and a web API

I am currently working on two separate applications, one developed in Angular and the other in web API. There is a function in my Angular application that calls a method in .NET Core. I would like to know if it is possible to debug the Angular function and ...

Tips for creating a window closing event handler in Angular 2

Can someone guide me on how to create a window closing event handler in Angular 2, specifically for closing and not refreshing the page? I am unable to use window.onBeforeunLoad(); method. ...

The replacement of classes in ReactJS using JavaScript seems to be malfunctioning

I have been attempting to change the class of a dynamic element when clicked, but none of my solutions seem to be working. Here is what I have tried: handleClick=(event,headerText)=>{ document.getElementsByClassName('sk-reset-filters') ...

Using jQuery to add a class to an input option if its value exists in an array

Looking for a way to dynamically add a class to select option values by comparing them with an array received from an ajax call. HTML <select id="my_id"> <option value="1">1</option> <option value="2">2</option> ...

Data in Angular is not getting transmitted properly through the routing system

I have a situation where I am sending data through routing and fetching it. Here's the code snippet for sending the data: navigateWithState(x) { console.log(x); this.router.navigateByUrl('/full-layout/add-form/1', { query ...

I am looking to transmit a JWT token to my backend using next-auth

In my current project using Next.js, I have implemented authentication with next-auth. This project follows the MERN stack architecture. I am facing an issue where I need to retrieve the JWT token and send it to my backend server using next-auth along wit ...

Is there a way to allow only the block code to shift while keeping the other span tags stationary?

Is it possible to change the text without affecting other span tags in the code? I want to make sure only this specific text is updated. How can I achieve that? var para_values = [ { content: "BRAND " }, { content: "MISSION" } ]; functi ...

What is the method for setting autofocus to the first input element within a loop?

I am currently working on a loop to display inputs, and I would like to be able to add focus to the first input element when it is clicked. Does anyone have any suggestions on how I can select that first element and set autofocus on it? ...

Dealing with problems in col-md display on tablet devices

When viewing on Full Screen and mobile, the ranges panel (class="col-md-3") displays correctly. However, on tablet screens, the left column is obscured by the youtube image panel (class="col-12 col-md-9"). I have attempted various adjustments to the div s ...

I'm interested in using JavaScript to create a URL for the current page with two additional parameters

Currently, I am utilizing the sharethis plugin within a smarty template. When sharing on Twitter, the link appears as follows: <span class='st_twitter_large' st_via="mediajobscom" st_url="MY URL HERE" displayText='Tweet'> My goa ...

Manipulating a textarea in jQuery by inserting a string and selecting a specific portion of it

Just as seen on SO with the B button: **bold text** Including that bold text is automatically highlighted and the cursor is placed right before the b ...