Error: The function was expecting a mapDiv with the type of Element, but instead undefined was passed - google

I have a map within a div tagged with #mapa. Whenever I try to plot a route on the map, it refreshes. I don't want the map to refresh, and here is the code I currently have:

<div style="height: 500px; width: auto;" #mapa>
  <google-map height="500px" width="100%" [zoom]="zoom" [center]="center" [options]="options" (mapClick)="click($event)">
    <map-marker #markerElem *ngFor="let marker of markers" [position]="marker.position" [label]="marker.label" [title]="marker.title" [options]="marker.options" (mapClick)="openInfo(markerElem, marker.info)" (mapDragend)="moveMap($event)">
    </map-marker>
    <map-info-window>{{ infoContent }}</map-info-window>
  </google-map>
</div>

If I remove the div with the reference #mapa and instead place the reference inside the <google-map> tag, I encounter an error and the map displays without any routes.

plotRouteOnMap() {
  const directionsService = new google.maps.DirectionsService;

  const directionsDisplay = new google.maps.DirectionsRenderer;
  const map = new google.maps.Map(this.mapa.nativeElement, {
    zoom: 7,
    center: {
      lat: this.markers[0].position.lat,
      lng: this.markers[0].position.lng
    }
  });

  directionsDisplay.setMap(map);
  directionsDisplay.setOptions({
    suppressMarkers: false,
    draggable: true,
    markerOptions: {
      icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
    }
  });

  directionsService.route({
    origin: {
      lat: this.markers[0].position.lat,
      lng: this.markers[0].position.lng
    },
    destination: {
      lat: this.markers[1].position.lat,
      lng: this.markers[1].position.lng
    },
    travelMode: google.maps.TravelMode.DRIVING,

  }, (response, status) => {
    if (status === google.maps.DirectionsStatus.OK) {
      console.log('STATUS OK');
      directionsDisplay.setDirections(response);
    } else {
      window.alert("Failed with status" + status);
    }
  });
}  

Answer №1

If you're looking to achieve your goal, the official @angular/google-maps module might be all you need.

Your HTML code could resemble something similar to this:

<google-map [options]="options">
  <map-marker *ngFor="let some of somearray" [icon]="...", [label]="...", [position]="..."></map-marker>
  <map-directions-renderer [directions]="..." [options]="..."></map-directions-renderer>
</google-map>

As for the trazarRoutaMapa() method, it could look somewhat like this:

trazarRoutaMapa(): void {
    const directionsService = new google.maps.DirectionsService; // ideally injected from constructor
    const request: google.maps.DirectionsRequest = {
      destination: {
        lat: this.markers[0].position.lat,
        lng: this.markers[0].position.lng
      },
      origin: {
        lat: this.markers[1].position.lat,
        lng: this.markers[1].position.lng
      },
      travelMode: google.maps.TravelMode.DRIVING
    };
    return directionsService.route(
    request, 
    (response, status) => {
      if (status === google.maps.DirectionsStatus.OK) {
        console.log('STATUS OK');
        directionsDisplay.setDirections(response);
      } else {
        window.alert("Error in status" + status);
      }
     });
  }

Note: This code was created in a text editor and not yet tested. Use with caution :)

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

Creating a Vue.js data object with items arranged in descending order

While working with vue.js, I encountered an issue in sorting the items stored in my data object. Currently, they are sorted in ascending order and I need to display them in descending order instead. Below is a snippet of my vue template: <div class="fo ...

Personalized cursor that blinks while utilizing window.history.replaceState

While navigating between sub-pages, I utilize the window.history.replaceState method to replace URLs in my web application. However, I have noticed that my custom cursor briefly blinks (replaced by cursor: default) when the current URL is replaced with a n ...

Incorporating an Angular Application into an Established MVC Project

I am working on an MVC project within an Area of a larger solution. My goal is to incorporate an Angular App into this area and integrate it with my MVC project. The catch is that this is not a .Net Core Mvc project. How can I configure my project to utili ...

"Troubleshooting the issue of Angular's select binding causing a disruption

The Angular version being used is 1.4.7. Within the model in question, there are two objects: 'systems', which is an array, and 'selectedSystem'. The desired outcome is for 'selectedSystem' to reference one of the objects wit ...

Buttons in HTML function properly on desktop but are ineffective on mobile devices

My website is almost complete, but I am facing some challenges with the mobile version. All buttons that use JavaScript are not functioning properly, whereas buttons with simple links work perfectly fine. This issue doesn't occur on Chrome when using ...

Socket IO: Error - The call stack has exceeded the maximum size limit

Whenever a client connects to my node.js server, it crashes with a 'RangeError: Maximum call stack size exceeded' error. I suspect there's a recursive problem somewhere in my code that I can't seem to find. This is the code on my serve ...

Creating a dynamic Bootstrap 5 carousel with active class on the first item and indicators

I am curious to know how to create a dynamic Bootstrap 5 carousel. Specifically, I want to know how to display indicators dynamically and add an active class to the first item of the carousel. In Bootstrap 4, it is done in the following way: $('#main ...

Use Jquery to add unique styles to specific words within a paragraph

I am looking to specifically style a particular word within a dynamic div for example, <div id="info">{$info}</div> prints <p>here you can get info about somnething. if you want more info about something then click here....</p> ...

What is the process for deleting a token from local storage and displaying the logout page in Next JS?

I developed a Next.js web application and am looking to display a logout page when the token expires, while also removing the expired token from local storage. How can I ensure that this functionality works no matter which page the user visits within the a ...

How can I retrieve data submitted in a POST request on my Node.js server

I'm having trouble sending form data to a node/express server using AJAX. After submitting, I keep getting redirected to a 'Cannot POST /' page. Although I can log the request object on the server side, the data from the form is missing. Wha ...

Is it normal for the protractor cucumber tests to pass without observing any browser interactions taking place?

Having recently started using protractor cucumber, I have created the following feature. Upon launching protractor protractor.conf.js, the browser opens and immediately closes, displaying that my tests have passed. Is this the expected testing behavior? Sh ...

Tips on how to showcase various information in distinct tabs using VueJS

I am currently working on a website project utilizing the VueJS framework and Vuetify template. My goal is to showcase different content under separate tabs, however, I'm encountering an issue where the same content is being displayed in all three tab ...

What could be causing the error "Type 'String' cannot be used as an index type" to appear in my TypeScript code?

My JavaScript code contains several associative arrays for fast object access, but I'm struggling to port it to TypeScript. It's clear that my understanding of TypeScript needs improvement. I've searched for solutions and come across sugges ...

Refresh the div by clicking it

$(window).load(function() { $("#Button").click(function() { alert('clicked') $("#div").load(" #div > *"); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script ...

Is there a way for my HTML file to connect with my CSS and JavaScript files stored in an Amazon S3 Bucket?

My current project involves hosting an HTML file as a website on AWS S3 in order to circumvent the CORS Policy. However, when I uploaded all my files into a new bucket, the HTML file was able to open but without accessing the accompanying CSS and JavaScrip ...

Generating formarray instances in Angular using data from MySQL records

I am currently working on a project where I need to populate formcontrols in formarray based on the data retrieved from a MySQL database. However, when I pass the success data from MySQL, I encounter an error that says "Cannot read property 'controls& ...

What are the circumstances under which JavaScript GCP libraries return null values?

My current project involves working with GCP and Firebase using typescript. I have been utilizing the provided libraries, specifically version 8 of Firebase, and have encountered some unexpected behavior. For instance (firebase, ver. 8.10.1) import 'f ...

Exploring the jQuery Solution for Enhancing Dojo Widget Framework

My experience with Dojo in the past has been great, especially with its widget infrastructure. Being able to easily separate code and HTML content, having a seamless connection with the require system used by Dojo, and the convenient builder that compresse ...

Update the component to display the latest information from the Bryntum grid table

In the Vue component, I have integrated a Bryntum grid table along with a bar chart. Clicking on one of the bars in the chart should update the data displayed in the Bryntum grid table. However, I've encountered difficulty in reloading the entire Bryn ...

Whenever my NodeJs encounters an unhandledPromise, it throws an error

exports.createNewTour = async (request, response) => { try { const newlyCreatedTour = await Tour.create(request.body); res.status(201).json({ statusCode: "success", details: { toursData: newlyCreatedTour, }, ...