Display the result of a Function in Angular using Typescript

I am working with angular and trying to display the result of a function in HTML. In my code snippet below, I am defining a function called 'geo' which returns the latitude and longitude values.

  var geo = function onLocationFound(e) {
  var radius = e.accuracy / 2;
  let marker = new L.Marker(e.latlng, {
    draggable: true,
    icon: Icon
  }).bindPopup(""+e.latlng);;
  map.addLayer(marker);
  return e.latlng
  }      
  this.latlng = geo;

However, when I try to display the 'latlng' value in HTML using {{latlng}}, it shows the entire function code instead of the expected return value. Can anyone point out where I might be making a mistake?

For reference, you can check out the original question here: assign function return value to some variable using javascript

Here is the corresponding .ts file:

import { Component } from '@angular/core';
import { icon,latLng, marker, polyline, tileLayer,Map, point } from 'leaflet';
/*import { GeoSearchControl, OpenStreetMapProvider } from 'leaflet-geosearch';*/
import * as L from 'leaflet';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
latlng:any

 public onMapReady(map: Map) {
    map.locate({setView: true, maxZoom: 16}); 
    /*map.on('click', <LeafletMouseEvent>(e) => { alert(e.latlng.lat); alert(e.latlng.lng); });*/
    var Icon = L.icon({
      iconUrl: 'leaflet/marker-icon.png',
      shadowUrl: 'leaflet/marker-shadow.png',
      iconSize:     [25,41], // size of the icon
      iconAnchor: [ 13, 41 ], // point of the icon which will correspond to marker's location
      shadowAnchor: [4, 62],  // the same for the shadow
      popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
  });

     function onLocationFound(e) {
      var radius = e.accuracy / 2;
      let marker = new L.Marker(e.latlng, {
        draggable: true,
        icon: Icon
      }).bindPopup(""+e.latlng);;
      map.addLayer(marker);
      this.latlng = e.latlng
      }      


 map.on('locationfound', onLocationFound);

  }

 
  

  

  googleMaps = tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', {
    maxZoom: 20,
    subdomains: ['mt0', 'mt1', 'mt2', 'mt3'],
    detectRetina: true
  });
  googleHybrid = tileLayer('http://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}', {
    maxZoom: 20,
    subdomains: ['mt0', 'mt1', 'mt2', 'mt3'],
    detectRetina: true
  });
  

  summit = marker([ 46.8523, -121.7603 ], {
    icon: icon({
      iconSize: [ 25, 41 ],
      iconAnchor: [ 13, 41 ],
      iconUrl: 'leaflet/marker-icon.png',
      shadowUrl: 'leaflet/marker-shadow.png'
    })
  });


  layersControl = {
    baseLayers: {
      'Google Maps': this.googleMaps,
      'Google Hybrid': this.googleHybrid,
      },
    }


  options = {
    layers: [this.googleMaps]
  };

  
};

Answer №1

Instead of calling the function itself, you are assigning the function to this.latlng. Remember to call the function by including parentheses:

this.latlng = geo();

Answer №2

Check out the code snippet below:

function displayLocation(e) {
      var radius = e.accuracy / 2;
      let marker = new L.Marker(e.latlng, {
        draggable: true,
        icon: CustomIcon
      }).bindPopup(""+e.latlng);;
      map.addLayer(marker);

      this.latlng = e.latlng
      }
    }

In HTML:

{{ latlng }}

If you need to transfer it elsewhere or to another function, simply pass this.latlng as a function parameter.

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

I possess an assortment of objects and I must retrieve specific information about them based on two data points

Managing a collection of items can be challenging, especially when filtering based on specific data points. For example, let's say we have a collection of action objects like {name: Detail}, {name: Spec}... and two data points determining which action ...

Error: 'delay' is not recognized as a valid function

I'm encountering an error message that reads as follows: $("div.valid_box").html(data.message).css("margin-left", "145px").css("width", "520px").show().delay is not a function [Break On This Error] $(...elay(10000).hide("slow", function() { within m ...

Ways for incorporating enumerate in HTML

Encountering an error when trying to reference an enum value. ERROR TypeError: Cannot read property 'Text' of undefined Is there a method to utilize this enum within the HTML section of a component? Enum definition: export enum InputType { ...

Is there a way to make a peer dependency optional in a project?

In the process of developing module A, I have implemented a feature where users can choose to inject a Winston logger into my module. As a result, winston becomes a peer dependency. However, when attempting to include module A in another module without th ...

Integrating Bootstrap-vue into your Webpack setup for seamless usage

After beginning a project with vuejs-templates and webpack, I decided to incorporate bootstrap-vue. Now, the challenge is figuring out how to implement a bootstrap button. In my code base, specifically in main.js, I have imported BootstrapVue: import Vu ...

Is there a way to stop "window.location.replace()" from being replaced or overridden?

Is there a method to safeguard against alterations or overrides of window.location.replace()? For instance, attempting to change it like this: window.location.replace = function(){ return "Hi" }. Initially, I experimented with using Object.free ...

Encountering problem with Http error in Angular2 rc1 Subscription

Attempting to incorporate my http service component using the following link: Here is my service component: import {Injectable} from '@angular/core'; import {Http, Response} from '@angular/http'; import {Observable} from 'rxjs/Rx ...

Navigating through error messages in NextJs 14 can be tricky, especially when faced with the dreaded "ReferenceError: document not defined" or "prerendering error". It's vital to pinpoint exactly which page

When attempting to run the build on my Next.js application, I encountered an error message that is not very informative given the number of files/pages in my project. How can I pinpoint the exact location of this error and determine the root cause? The pro ...

The assets on the page are not loading inside their designated containers

While conducting functional tests with nightwatch.js, I encountered a discrepancy between my local environment and the containerized environment. In the container environment, which is crucial for integrating into my CI pipeline and running automated tests ...

There are certain lines of JavaScript/Node.js code that are failing to execute

app.get is not being executed. I have also attempted to include app.listen(3000). My goal is to retrieve the parameter passed from the first web page. This code is designed to fetch parameters sent by another web page and then construct a MySQL query and ...

Utilizing backbone-forms in Typescript: A beginner's guide

Currently in my project, I utilize backbone.js along with typescript. My goal is to incorporate backbone-forms for form creation, however I am unable to locate a typescript definition file (d.ts) for this specific backbone plugin. Despite my attempts to cr ...

Providing input to a nested mongoose query

I can't figure out why I keep experiencing 504 Gateway timeouts. app.get("/api/exercise/log", function(req,res) { let userId = req.query.userId; let from = req.query.from; let to = req.query.to; let limit = req.query.limit; console.log("lim ...

Localization & Internationalization in Angular 6 CLI for enhancing multi-language functionality

Our Application is built on Angular 6 and we are looking to incorporate multilingual support. Please advise on how we can enable localization and internationalization in Angular 6. This pertains specifically to the Angular 6 version. ...

How can we achieve a gradual and smooth stop in Three.js OrbitControls instead of an abrupt halt while panning?

How can I configure the OrbitControls to gradually bring a scene to a standstill while panning, like on this website, instead of stopping instantly? Below is my code snippet: controls = new THREE.OrbitControls( camera, renderer.domElement ); controls.mou ...

DiscordjsError: The client attempted to use a token that was not accessible

Hey there, I'm currently working on implementing a bot for my server and encountered an issue while attempting to create a member counter for voice channels. After completing the setup, I ran node index.js in the terminal, only to receive an error ind ...

JavaScript - Struggles with developing a personalized AJAX function

I have been working on creating a function to manage my AJAX post requests. While I have successfully sent the data, I am encountering difficulties with receiving the response. The function in question is named ajaxPost(paramArray, target). It takes param ...

Material-UI React Native components: Injecting Styles without Props

import {createStyles, WithStyles} from "@material-ui/core"; const styles = (theme: Theme) => createStyles({ root: {} }); interface MyProps extends WithStyles<typeof styles> { } export class MyComponent extends Component<MyProps ...

Freshening up the data source in a Bootstrap Typeahead using JavaScript

I'm trying to create a dropdown menu that displays options from an array stored in a file called companyinfo.js, which I retrieve using ajax. The dropDownList() function is called when the page loads. function dropDownList (evt) { console.log("dr ...

Adding an image in HTML from a different drive - step-by-step guide!

Currently, I am immersing myself in HTML, CSS, and JavaScript as I gear up for my upcoming school project centered around frontend development. Here's the issue I encountered. While attempting to insert an image into one of my HTML files, I ran into ...

What is the best way to avoid curly braces in an Angular template?

If I need to show the following string, including the {{ }}, in an Angular 2+ template: Hello {{name}}, how are you?" Note: The entire string will be hardcoded, not from a variable. What is the optimal method to encode the curly braces so they are not ...