I want to know the best way to send latitude and longitude coordinates from an external source in order to generate a

  • Looking for advice on customizing a working code that uses leaflet angular to place markers with predefined latitudes and longitudes. I want to be able to customize this by passing latitudes and longitudes when the addmarker button is pressed. Any suggestions on how to achieve this?

    The latitude and longitude information is not available when the page loads, it must only be passed when the add marker button is pressed.

import { Component, OnChanges } from "@angular/core";
import "leaflet/dist/leaflet.css";
import * as L from "leaflet";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  map;
  markers: L.Layer[] = [];


  markerIcon = {
    icon: L.icon({
      iconSize: [25, 41],
      iconAnchor: [10, 41],
      popupAnchor: [2, -40],
      // specify the path here
      iconUrl: 'leaflet/marker-icon.png',
      shadowUrl: 'leaflet/marker-shadow.png'
    })
  };

  public options = {
    layers: [
      L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
        maxZoom: 18,
        attribution: ""
      })
    ],
    zoom: 10,
    center: L.latLng(40.7128, 74.0060)
    //center: L.latLng(this.lat, this.long);
  };

getLatLong() {
this.lat = 40.7128;
this.long = 74.0060;
this.addMarker(this.lat, this.long);

  }


  addMarker(lat, long) {

    const newMarker = L.marker([40.7128, 74.0060], this.markerIcon);
    //const newMarker = L.marker([this.lat, this.long], this.markerIcon);

    this.markers.push(newMarker);

    newMarker.addTo(this.map);
  }

  onMapReady(map: L.Map) {
    this.map = map;
    // Do stuff with map
  }
}




<div
style="height: 90vh;"
leaflet
[leafletOptions]="options"
(leafletMapReady)="onMapReady($event)"
></div>

<button (click)="addMarker()">
add marker
</button>
<button (click)="getLatLong()">
  getLAtLong
  </button>


Answer №1

To specify the coordinates you desire, simply include them as arguments within the addMarker() function like this:

<button (click)="addMarker(46.8523, -121.7603)">
  add marker
</button>

No need for getLatLong or an additional button.

Afterwards, utilize the map instance to adjust the map center location:

this.map.panTo(new L.LatLng(lat, lng));

Check out a demo here

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

Using Typescript in a definition file requires classes and interfaces to be included in the compiled .js file

I am currently working on a Typescript project that consists of two crucial files: app.ts models.d.ts The initial lines of code in app.ts are as follows: ///<reference path="models.d.ts"/> 'use strict'; import * as fs from 'async-f ...

Choose an alternative following the start-up phase

I have been searching for solutions on various platforms, including Stack Overflow, but nothing seems to work for me. I am struggling with selecting the first option after initializing the box because currently it is choosing a blank option that is not eve ...

Troubleshooting an Angular application in Intellij using Chrome on a Windows operating system

I've been searching for a long time for a way to debug an Angular app in IntelliJ using Chrome on Windows. So far, I have not been successful in attaching a debugger to Chrome. I have tried launching Chrome with --remote-debugging-port=9222 and numer ...

Error: Found an unconventional token "e" in JSON data at position 1 during parsing in JSON.parse function

Is there a way to retrieve a string value by calling an API in Angular? Here is my approach: Service file - public getRespondDashboardUrl(): Observable<any> { return this.http.get(`ref/RespondDashboardUrl`); } Component File respondDashboar ...

Dynamic table row that expands to show additional rows sourced from various data sets

Is there a way to expand the table row in an angular-material table when it is clicked, showing multiple sets of rows in the same column as the table? The new rows should share the same column header but not necessarily come from the same data source. Whe ...

Bidirectional binding of ngModel across components with validation

I am attempting to link a value from the parent component to the child component for reusability. parent-component.ts profile:any = {name:"", mobile:""} Parent-component.html <app-profile-name label="Name" [(name)]="profile.name"></app-profil ...

After compiling the code, a mysterious TypeScript error pops up out of nowhere, despite no errors being

Currently, I am delving into the world of TypeScript and below you can find the code that I have been working on: const addNumbers = (a: number, b: number) => { return a + b } Before compiling the file using the command -> tsc index.ts, the ...

Tips for sending data in Angular 8's Http GET method within a service class, especially when the backend requires a dictionary format

I am working on a C# backend with an HttpGet method that is expecting a dictionary as request parameters. public async Task<IActionResult> Search([BindRequired, FromQuery] IDictionary<string, object> pairs) Currently, my frontend is built in A ...

Tips for addressing a situation where an npm package encounters issues during AOT compilation

As a newcomer to web development, I am currently struggling with an issue that has me stumped. Within my web application, I am utilizing the npm package called @uniprank/ngx-file-uploader (https://www.npmjs.com/package/@uniprank/ngx-file-uploader). While ...

Probability of an event occurring when represented as whole numbers in percentage form

Currently, I'm developing a unique job system within a Discord bot that allows users to mine various types of ores. The probability of receiving specific ores is based on the user's mining skill level, which is stored in a database and can vary a ...

Exploring TypeScript's type discrimination with objects

When working with TypeScript, type discrimination is a powerful concept: https://www.typescriptlang.org/play#example/discriminate-types But is it possible to achieve something like this? type A = {id: "a", value: boolean}; type B = {id: "b ...

How can we set up the Typescript Compiler to recognize typings and modules effectively?

I have been working on a TypeScript project with the following structure: <work folder>/Scripts/ (project root) +-- App +--- subfolder1 +--- subfolder2 +-- typings After openi ...

Error involving key mismatch between TypeScript inherited interface and literal string type

There are 3 interfaces (A, B, and C) that all extend from a shared interface (Common). Additionally, there is a container type which holds arrays of these 3 interfaces (Container). The goal is to select one of the arrays and extract a common property from ...

What is the reason for `downlevelIteration` not being enabled by default?

When directing towards ES5 and using the spread operator ... to convert an Iterator to an Array, it prompts the need for the -downlevelIteration compiler option. Enabling this option allows the spread operators to function without any errors. I'm cur ...

Is it possible to customize the open/close icon on a PrimeNG Panel?

Looking to customize the open/close icon on the Angular PrimeNG panel component. At the moment, it's displaying a plus/minus sign, but I'd like to switch it out for a chevron up/chevron down icon instead. While I've managed to add extra icon ...

Retrieving the row value of a checkbox in an Angular table

I'm facing a challenge where I have a table with three columns, one of which is a checkbox. Here is an image for reference: https://i.sstatic.net/4U6vP.png Here is the code snippet: <div nz-row> <nz-table nz-col nzSpan="22" [nzLoading] ...

Angular2 import functions properly on the Windows operating system, however, it encounters issues on the Linux

import { Injectable } from '@angular/core'; import { Http, Response, Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { User } from './../../class/User'; I am encountering the fol ...

Angular 12: Ensure completion of all data fetching operations (using forkJoin) prior to proceeding

Within my ngOnInit function, I am looking for a way to ensure that all requests made by fetchLists are completed before moving forward: ngOnInit(): void { this.fetchLists(); this.route.params.subscribe(params => { this.doSomethingWit ...

External function does not support jQuery types

In my theme.js file, I currently have the following code: jQuery(function ($) { accordion($) }) const accordion = ($) => ... By placing the accordion function directly into the jQuery function, Typescript is able to assist with the installed jquery ...

Avoid repeating the base URL when creating services using the intercept service concept

Greetings, I must begin with an apology for any confusion in my explanation of the issue at hand. Currently, as part of a project I am working on, the Base URL or Environment URL is defined within the InterceptService. However, there seems to be an anomal ...