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

How can I restrict the return type of a generic method in TypeScript based on the argument type?

How can we constrain the return type of getStreamFor$(item: Item) based on the parameter type Item? The desired outcome is: When calling getStream$(Item.Car), the type of stream$ should be Observable<CarModel> When calling getStream$(Item.Animal), ...

Instructions for adding a new property dynamically when updating the draft using immer

When looking at the code snippet below, we encounter an error on line 2 stating Property 'newProperty' does not exist on type 'WritableDraft<MyObject>'. TS7053 // data is of type MyObject which until now has only a property myNum ...

Dealing with website links in Next.js and Chakra-UI: Tips and Tricks

When incorporating react linkify directly with chakra-ui components such as Text, the links cannot be managed. Issue Example import Linkify from 'react-linkify'; import {Box, Text} from '@chakra-ui/react'; export default function Usag ...

Mapping object array values to the same key in Angular is a common task that can

Recently, I encountered an object that looks like this: const product = { name: 'watch', color: ['brown', 'white'] } Here's what I'm aiming for: I want to transform this object into the following format: name: ...

Updating a value using jQuery AJAX techniques

Using jQuery AJAX, I am loading the content of a page in this way: $(document).ready(function(){ $('#next').click(function(event){ $.ajax({ url: "load.php?start="+$('#lastid').text(), success: function(html){ $("#results"). ...

Tips for launching different web browsers via hyperlinks?

My app has a link that I want mobile users from apps like LinkedIn to open in a browser such as Safari. I attempted this: <a href="safari-https://meed.audiencevideo.com">May open on Safari</a>' However, when I click the link, it opens i ...

NextJS is throwing an error: The prop `href` in `<Link>` should be a `string` or `object`, but it received `undefined` instead

I've encountered an issue while trying to integrate a header section from a GatsbyJS project into my NextJS project. The error message I'm receiving is: "Error: Failed prop type: The prop href expects a string or object in <Link>, but ...

utilize Java version specifically designed for integrating with Angular framework and SOAP web services

One question I've been pondering: we currently have a project built on Java 6 and GWT, but we're considering migrating to Angular (using SOAP web services). Will Java 6 be compatible with Angular for the backend, or will we need to upgrade to Jav ...

Can anyone help with displaying a PNG image in Vue/Node/Express? I am struggling to show the image that I sent from a Node.js server to a Vue app client

In my Node/Express application, I've set up a route like this: app.get('/get-image', function(req, res) { ... res.sendFile(path.join(__dirname, '..', account.profileImg)); }) Now in my client-side Vue app, I'm tryi ...

Error in jQuery submenu positioning issue

I am attempting to design a menu that opens when the parent element is clicked and closes when the mouse leaves the previously opened one. It should operate from left to right. Here is an example: <ul class="menuFirst"> <li><im ...

Don't forget to save the selected tab in Angular 5 using a bootstrap tabset

Using the tabset feature from Bootstrap (specifically ngx-bootstrap.es2015.js) in an Angular 5 application has been mostly successful. However, a common issue arises when navigating between components. When transitioning back to the component with the tabs ...

Resolving TypeError: matchesSelector method is not recognized within React component

I am currently integrating masonry-layout from the official website to create a masonry grid within my component. However, I encountered an issue where clicking on a rendered element triggers the error message TypeError: matchesSelector is not a function. ...

Exploring the possibilities of jQuery with Accordion functionality and creating dynamic multiple menus

Incorporating the Wayfinder and Accordion menus, I have set up a two-level menu structure for the left column. The structure looks like this: <ul class="accordion">: Menu 1 Sub-menu 1.1 Sub-menu 1.2 Sub-menu 1.3 Menu 2 Sub-menu 2 ...

The HTML status code is 200, even though the JQuery ajax request shows a status code of 0

My issue is not related to cross site request problem, which is a common suggestion in search results for similar questions. When attempting to make an ajax request using jquery functions .get and .load, I'm receiving xhr.status 0 and xhr.statusText ...

Obtain image URL from object properties using AngularJS

Just starting out with Angular JS and I have a question. I'm currently working on a project and I have a solution in mind, but I was wondering if there's a more "angular-esque" approach that I could take. The idea is for each videoid, there wou ...

What is the best way to capture the inputs' values and store them accurately in my object within localStorage?

Is there a more efficient way to get all the input values ​​and place them in the appropriate location in my object (localStorage) without having to individually retrieve them as shown in the code below? Below is the function I currently use to update ...

sequencing the compilation of Node.js modules

I am facing an issue with my node application involving multiple interdependent modules exported using module.exports. These modules include mongohelper, transaction, server, conhandlr, and appmin. Compile order- mongohelper transaction server (..the ...

The functionality of Angular 6 Material Nested Tree is disrupted when attempting to use dynamic data

In Angular 6, I am utilizing mat-tree along with mat-nested-tree-node. My objective is to dynamically load the data when the user toggles the expand icon. Attempting to apply the dynamic data concept from the Flat Tree example provided in Material Example ...

How to automatically set focus in a text box when a Kendo Window is opened

I am working on a project where I need to set the focus on the first field of a kendo-window when it opens after clicking on a button. I used ViewChild to declare the field, but it is showing as undefined when the window is opened because it hasn't be ...

Display data from two arrays in real-time

The following data is available: "PensionPlanSummary": [ { "Type": "DefinedContributionPension", "Participants": [ { "Year": 2018, "Value": 425.0 } ...