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

Having trouble importing the module in NestJS with Swagger?

Currently, I am in the process of developing a boilerplate NestJS application. My goal is to integrate @nestjs/swagger into the project. However, I have encountered an import error while trying to include the module. npm install --save @nestjs/<a href=" ...

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 ...

When running npm start on a Windows system, an error message stating "Node.js version 14.9.0 detected" is displayed

Encountering an error with the npm start command: Node.js version v14.9.0 detected. The Angular CLI requires a minimum Node.js version of either v14.15, or v16.10. Please update your Node.js version or visit https://nodejs.org/ for additional instructions ...

Testing the functionality of NgRx effect through unit testing

Looking to unit test a functional effect found in this code snippet export const loadUsers = createEffect( (actions$ = inject(Actions), usersService = inject(UsersService)) => { return actions$.pipe( ofType(userActions.getUser), exhaus ...

Tips for navigating to a specific item in a react native list?

Is it possible to scroll to a specific element within a list based on another element in the list? For example, if you have a list [a,b,c,d], and each element is a touchableopacity with text a b c d respectively, can you set it up so that clicking on &apos ...

Retrieving information from the Dog API using axios and storing the results in a fresh array

Currently, I am working on a NextJS app using Typescript. My issue lies in the functionality aspect of the application. I am utilizing the Dog API to retrieve all the breeds names and store them in a new array of arrays. Each sub-array contains the breed a ...

What steps can be taken to avoid an abundance of JS event handlers in React?

Issue A problem arises when an application needs to determine the inner size of the window. The recommended React pattern involves registering an event listener using a one-time effect hook. Despite appearing to add the event listener only once, multiple ...

When trying to use the exported Ionic 3 class in TypeScript, the error "Cannot find name 'ClassName'" occurs

When working on my Ionic 3 Application, I encountered an error stating "Cannot find name" when trying to use certain plugins. I initially imported the plugin like this: import { AndroidPermissions } from '@ionic-native/android-permissions'; and ...

Is there a way to verify the availability of an authenticated resource without triggering a pop-up for credentials in the browser?

I am facing the challenge of fetching data from a web service located on a different server without knowing if the user has an active session on that server. If the user does have a session, I want to retrieve the data automatically. However, if they do no ...

What could be the reason for the esm loader not recognizing my import?

Running a small express server and encountering an issue in my bin/www.ts where I import my app.ts file like so: import app from '../app'; After building the project into JavaScript using: tsc --project ./ and running it with nodemon ./build/bin ...

I'm new to Angular, so could you please explain this to me? I'm trying to understand the concept of `private todoItems: TodoItem[] = []`. I know `TodoItem` is an array that

//This pertains to the todoList class// The property name is todoItems, which is an array of TodoItem objects fetched from the TodoItem file. I am unable to make it private using "private todoItems: TodoItem[] = []," is this because of Dependency Injectio ...

It is possible that req.user may be undefined, especially when using express and passport.js

I am facing an issue with my Node.js TypeScript authentication system that utilizes passport. The problem arises when I attempt to access req.user in a specific route, resulting in the error message: Object is possibly 'undefined'. This behavio ...

Make sure to include the @ symbol before "angular" in the package.json file when setting

Can someone explain to me why the Angular 2 quickstart guide suggests using a package.json file structured like this: { "name": "angular2-quickstart", "version": "1.0.0", "scripts": { "start": "tsc && concurrently \"npm run tsc:w&bs ...

Displaying a React component within a StencilJS component and connecting the slot to props.children

Is there a way to embed an existing React component into a StencilJS component without the need for multiple wrapper elements and manual element manipulation? I have managed to make it work by using ReactDom.render inside the StencilJS componentDidRender ...

What is the best method for inserting a hyperlink into the JSON string obtained from a subreddit?

const allowedPosts = body.data.children.filter((post: { data: { over_18: any; }; }) => !post.data.over_18); if (!allowedPosts.length) return message.channel.send('It seems we are out of fresh memes!, Try again later.'); const randomInd ...

The impact of redefining TypeScript constructor parameter properties when inheriting classes

Exploring the inner workings of TypeScript from a more theoretical perspective. Referencing this particular discussion and drawing from personal experiences, it appears that there are two distinct methods for handling constructor parameter properties when ...

Error: Jest + Typescript does not recognize the "describe" function

When setting up Jest with ts-jest, I encountered the error "ReferenceError: describe is not defined" during runtime. Check out this minimal example for more information: https://github.com/PFight/jest-ts-describe-not-defined-problem I'm not sure what ...

Data bindings encapsulated within nested curly braces

I am currently utilizing Angular2 in my application. Within my html file, I have a *ngFor loop set up like so: <div *ngFor="let element of array"> {{element.id}} </div> Next, I have an array containing objects structured as follows: some ...

What causes the app to crash in release mode when importing a TypeScript component, while no issues arise in debugging?

Having an issue with importing a bottom sheet written in typescript into a class component. It works correctly in debugging mode but unfortunately not in release mode. Despite checking the logcat, no readable error code or message is being printed. Even a ...

What is the best way to iterate over an Angular HTTP Response?

As a newcomer to Angular, I am working on mastering the process of uploading files and calling an API for validation. The API responds with a list of JSON validation errors based on specific file values. I am currently struggling to iterate through these ...