Tips for transferring Google Maps place array data from Angular 5 TypeScript to HTML

I am new to Angular 5 and I am attempting to display nearby restaurant results using Google Maps in Angular 5. However, I am unsure of where to create the array in TypeScript and how to pass this array into the HTML when searching for "restaurant". I have attempted to create a JavaScript function to capture the value and pass it to the component's HTML, but I have not been successful.

Can anyone assist me with this?

ngOnInit() {
      var mapProp = {
        center: new google.maps.LatLng(3.147609, 101.698625),
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

      this.map = new google.maps.Map(this.gmapElement.nativeElement,mapProp);
      var map = this.map;
      var infoWindow = new google.maps.InfoWindow;

      var input = <HTMLInputElement>document.getElementById('pac-input');

      var searchBox = new google.maps.places.SearchBox(input);


      map.addListener('click',function(event) {



   infoWindow.setPosition(event.latLng);

   infoWindow.open(map);


    });



      map.addListener('bounds_changed', function() {

        searchBox.setBounds(map.getBounds());
      });

      var markers = [];

      searchBox.addListener('places_changed', function() {


        var places = searchBox.getPlaces();

        if (places.length == 0) {
          return;

        }


        // Clear out the old markers.
        markers.forEach(function(marker) {

          marker.setMap(null);


        });
        markers = [];

        // For each place, get the icon, name and location.
        var bounds = new google.maps.LatLngBounds();      


        places.forEach(function(place) {


          if (!place.geometry) {
            console.log("Returned place contains no geometry");
            return;
          }


          var icon = {
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(25, 25)
          };




          // Create a marker for each place.
          markers.push(new google.maps.Marker({
            map: map,
            icon: icon,
            title: place.name,
            position: place.geometry.location
          }));
            console.log(place.name);
          if (place.geometry.viewport) {
            // Only geocodes have viewport.

            bounds.union(place.geometry.viewport);
          } else {
            bounds.extend(place.geometry.location);

          }
        });
        map.fitBounds(bounds);
      });
  }

}

Ben

Answer №1

Unfortunately, I am unable to provide comments at this time. Have you considered why passing an array to your HTML is necessary? One alternative suggestion would be to utilize TypeScript to manipulate the DOM and dynamically add elements to display in your HTML.

When considering your question, a potential workflow that comes to mind includes:

  • Utilizing navigator.geolocation to obtain the user's position (refer to this link for more information)
  • Using nearby search requests to fetch places in proximity (refer to this link for guidance on this step)
  • Compiling a list of relevant details (such as place names, exact locations, markers on the map, links to user reviews) and generating corresponding HTML elements (consider incorporating JQuery to streamline this process if needed)

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

react-vimeo not firing onPause and onPlay events

I am facing an issue with triggering props when playing a Vimeo video on my webpage. Here's a snippet of my code: import Vimeo from '@u-wave/react-vimeo'; const handleVimeoProgress = (data: any) => { console.log('Progress:' ...

Retrieving the data from the <input> tag using TypeScript

I'm currently working on retrieving user input values from a form. While vanilla JavaScript allows me to easily target elements and get their values using the .value method, I've encountered some challenges with TypeScript. Despite TypeScript bei ...

Creating actions safely with redux typesafety

I've made a mistake several times by forgetting to properly extract the connected action creator from props, as shown below: import {actionCreator} from 'my-actions'; interface Props { actionCreator: typeof (actionCreator); } const Foo: ...

What is the best way to access the original observed node using MutationObserver when the subtree option is set to

Is there a way to access the original target node when using MutationObserver with options set to childList: true and subtree: true? According to the documentation on MDN, the target node changes to the mutated node during callbacks, but I want to always ...

Validation in Angular 2+ for child components

I am seeking assistance with Angular as I do not have expert knowledge in it. My goal is to implement form validation in a component named "viewForm". This form is created using an object array loop called "points". Towards the end of the "viewForm", I hav ...

Checkbox: Customize the appearance of the root element

I am trying to modify the root styles of a Checkbox component, but it is not working as expected. Here is my code: <CheckboxItem onChange={()} checked={isChecked} label="Show Checkb ...

Storing information in firebase using data structuring

While I initially passed an array to Firebase to store data, it proved to be inefficient when querying the data. As a result, I am now considering storing the data in mapping format. However, I am unsure of how to proceed with this. { "ClassDetails": ...

Solidjs: Implementing a Map in createStore does not trigger updates upon changes

As a beginner in solidjs, I might have missed something important. In the code snippet below, I am trying to understand an issue: const [state, setState] = createStore({ items: new Map() }); // e.g. Map<number, string> In a component, suppose I want ...

Failed deployment of a Node.js and Express app with TypeScript on Vercel due to errors

I'm having trouble deploying a Nodejs, Express.js with Typescript app on Vercel. Every time I try, I get an error message saying "404: NOT_FOUND". My index.ts file is located inside my src folder. Can anyone guide me on the correct way to deploy this? ...

The addition of types/cors in Express Typescript causes my POSTMAN request to hang indefinitely

I am experiencing an issue with my React web app and Express TypeScript backend. Previously, my POST request was functioning well, but now it seems to hang indefinitely on Postman without returning any errors. issueController.ts import { RequestHandler } ...

Evaluating whether an imported function, which serves as a dependency of an adapter, is being invoked with accurate parameters within the adapter using the Jest testing framework

Here is how my test looks import { SlugGeneratorAdapter } from './slug-generator-adapter' import slugify from 'slugify' describe('SlugGenerator Adapter', () => { test('Should call the slug generator with the correct ...

When Typescript compiles to JavaScript, it may result in code that appears to be a function

In the following typescript code snippet: export enum UID { FACTORY, ROBOT } we see how it compiles to javascript: (function (UID) { UID._map = []; UID._map[0] = "FACTORY"; UID.FACTORY = 0; UID._map[1] = "ROBOT" ...

TypeScript shared configuration object utilizing type declarations

Currently, I am working on developing an API library and I have a question regarding how to approach the endpoint configuration issue in Node.js with TypeScript. My goal is to have all endpoint configurations contained within a single entity. The current ...

Unable to locate a declaration file for the 'mymodule' module

After attempting to import my test module by installing it with npm i github.com/.../..., the code is functioning properly. However, when I opened it in VSCode, an error message popped up: Could not find a declaration file for module 'estrajs'. & ...

Tips for widening a union data type in a different section?

Is there a way to expand on a union type from another module? Below is an example showcasing the need for this, but I encountered a ts(3200) error due to duplicate identifiers. The Core module @org/core defines a union type called OptionType: // Defined i ...

Typescript service wrapper class returning Axios HEAD request

I am attempting to retrieve the header response using a custom Axios HTTP service wrapper. axiosClass.ts import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios"; class Http { private instance: AxiosInstance | null = n ...

Locations of TypeScript 2.1 Definitions in Visual Studio 2015

Struggling to develop a React-Redux web application in Visual Studio 2015 using TypeScript. I encountered issues while trying to import modules after adding react and redux via NPM along with @types. Initially, the red squiggle appeared for "react" module, ...

Having trouble with the rowNode functionality in PrimeNG TreeTable

I am currently utilizing the PrimeNG Treetable component from https://www.primefaces.org/primeng/#/treetable I seem to be encountering issues with retrieving data from the service. Below is a snippet of my code: HTML <p-treeTable [value]="temp"> & ...

Is there a way to ensure that the onChange event of ionic-selectable is triggered twice?

I've been working with an ionic app that utilizes the ionic-selectable plugin, and for the most part, it's been running smoothly. However, I encountered a rare scenario where if a user on a slow device quickly clicks on a selection twice in succe ...

How can TypeScript handle unresolved generics within conditionals using "catch"?

For quite some time now, I've been on the quest to find a real-life example that isn't overly complex for this scenario. Let's see if this one fits the bill. The context here relates to our usage of immer, which provides a Draft type struct ...