Angular4 Leaflet Map encountering errors

Here is the template:

<div id="mapid" style="height: 500px"></div>

After installing Leaflet and the typings for Leaflet, I encountered an error stating that the map container was not found. To solve this, I added its import.

This is the controller code:

    import { Component, OnInit, EventEmitter, Output } from 
    '@angular/core';
import * as L from 'leaflet';
import { Map } from 'leaflet';

@Component({
  selector: 'app-leafletmap',
  templateUrl: './leafletmap.component.html',
  styleUrls: ['./leafletmap.component.css']
})
export class LeafletmapComponent implements OnInit {
  mymap = L.map('mapid').setView([29.6516, -82.3248], 13);

  L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}',
   {
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, 
    <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
    maxZoom: 18,
    id: 'mapbox.streets',
    accessToken: '*****************************'
  }).addTo(mymap);

  popup = L.popup();
  marker: any;

  onMapClick(e) {
    if (marker != undefined)
      mymap.removeLayer(marker)
    marker = new L.Marker(e.latlng, { draggable: true });
    mymap.addLayer(marker);
    popup.setLatLng(e.latlng).setContent("You clicked the map at " + e.latlng.toString()).openOn(mymap);
  }
  
  mymap.on('zoomend', function() {
    console.log(mymap.getZoom());
  })
  
  mymap.on('click', onMapClick);

  constructor() { }

  ngOnInit() {
  }

}

I am uncertain about whether I am correctly passing access tokens and initializing variables in TypeScript, as I wrote this code based on a tutorial that used regular JavaScript.

Answer №1

If you're looking to work with leaflet, I've got a code snippet that's fully functional for you to try out.

To get started, make sure to install the following npm module:

npm install @asymmetrik/ngx-leaflet --save
For more information, check out: https://github.com/Asymmetrik/ngx-leaflet

Your component.ts file should look something like this:

private map: L.Map;

options = {
        layers: [
            L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 15 })
        ],
        zoom: 4,
        center: L.latLng([39.878868, -100.357010])
    };

onMapReady(map: L.Map) {
    this.map = map;
}

In your component.html file:

<div leaflet
     [leafletOptions]="options"
     (leafletMapReady)="onMapReady($event)">
</div>

Don't forget to update your app.module.ts file as well:

imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        AppRoutingModule,
        BrowserAnimationsModule,
        LeafletModule.forRoot() // Make sure to include leaflet here.
    ]

Start off with my basic setup and then feel free to customize it by adding your own options and logic to the onMapReady function.

Update: If you need to reference specific elements from leaflet, such as MapOptions in a particular component, simply import leaflet like this: import * as L from 'leaflet'; and then use L.Map, L.MapOptions, etc.

Another Update: It's also crucial to install types using npm install @types/leaflet

Answer №2

Encountered a similar issue where I received the error message:

Module '"leaflet"' does not have a 'MapOptions' member
. In my case, resolving the problem involved removing the leaflet-types package (npm uninstall @types/leaflet)

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

Tips for preventing my component from being duplicated during the development process

I found a helpful guide on creating a JavaScript calendar in React that I am currently following. After implementing the code, I successfully have a functional calendar UI as shown below: // https://medium.com/@nitinpatel_20236/challenge-of-building-a-cal ...

Combining class and data within an iteration while utilizing ngFor

I have a dynamic table with rows generated using ngFor <tbody> <tr *ngFor="let item of Details"> <div class="row details-row row-cols-lg-2 row-cols-1" *ngIf="closureDetails"> <div ...

Switch between div elements in Angular 2 while dynamically changing their values depending on a specific condition for displaying or hiding

After referring to the solution found in (Hide/show individual items inside ngFor), I am facing a challenge regarding setting the value of pinMe[j] based on a condition. In my scenario, I need to toggle between div elements while also determining what shou ...

What is the best way to showcase the outcome of a function on the user interface in Angular 2?

The code snippet below was originally in my .component.html file: <div class="someContainer"> <div class="text--bold">Display this please:</div> <div>{{ myObject.date ? '2 Jun' : 'Now' }}</div&g ...

A bespoke Typescript implementation of nested lists containing numbers

Currently, I am trying to figure out how to declare and populate a TypeScript list of lists. The structure of the list should be as follows: List<CustomList<>, number> Typically, I would create a standard list like this: someList: { text: a ...

What does the "xxx" parameter represent in the ng g universal xxx command when using AngularCLI 6+?

In this scenario, what is the purpose of morningharwood-server? Can we find it referenced in the code? ng generate universal morningharwood-server --client-project morningharwood ...

Issue with Angular 6 Share module functionality not functioning as expected

While creating my Angular 6 application, I encountered an issue with sharing a header across multiple pages. I tried including it but it doesn't seem to be working. Can anyone point out what I might be doing wrong? For a demonstration, you can visit . ...

Creating an empty TypeScript variable with type FileList can be achieved by declaring the variable and initializing it with

After completing a coding test that required building a react app for uploading files using Typescript, I encountered a dilemma. Specifically, I needed to use the useState hook to store the uploaded file and set its default value. Typically, setting the de ...

Leveraging Angular's capability to import files directly from the assets

I recently installed a library via npm and made some modifications to one of the modules. python.js If I delete the node_modules folder and run npm install, I am concerned that I will lose my changes. Is there a way to preserve these modifications by mov ...

Requesting for a template literal in TypeScript:

Having some trouble with my typescript code, it is giving me an error message regarding string concatenation, const content = senderDisplay + ', '+ moment(timestamp).format('YY/MM/DD')+' at ' + moment(timestamp).format(&apo ...

Using a try block inside another try block to handle various errors is a common practice in JavaScript

In an effort to efficiently debug my code and identify the location of errors, I have implemented a try-catch within a try block. Here is a snippet of the code: for (const searchUrl of savedSearchUrls) { console.log("here"); // function will get ...

Using Express middleware in a TypeScript Express application

I'm currently converting the backend of an ExpressJS application to Typescript. While working on the auth.routes.ts file, I encountered an issue with the middleware (authMiddleware). It seems like there might be a typing error, as the same code in the ...

Setting up TypeScript compilation for TS modules in an AngularJs application: A comprehensive guide

After conducting a test, it has come to my attention that TypeScript 2.6.2 imposes a requirement where imported elements need to be used in a new before the module is referenced in a require. The test is based on the following code snippets extracted from ...

"When attempting to render a Node inside the render() method in React, the error message 'Objects are not valid as a React child' is

On my webpage, I have managed to display the following: export class OverworldComponent extends React.Component<OverworldComponentProps, {}> { render() { return <b>Hello, world!</b> } } However, instead of showing Hello, ...

Unleash the power of Typescript and Node to create detailed REST API documentation!

Is it possible to generate REST API documentation using https://github.com/TypeStrong/typedoc similar to what can be done with ? I would appreciate any recommendations on leveraging TypeScript types for creating REST API documentation (specifically within ...

Pass the API_BASE_URL parameter from the Angular 7 configuration

Currently, I am developing an Angular 7 Application using es6 Javascript and Swagger integration. My current challenge involves adding the configuration to APP_INITIALIZER in the app.module file: export class SettingsProvider { private config: AppConfi ...

Tips and tricks for setting up a functional react select component using Material UI

Having an issue with React Select material UI where the dropdown select is not functioning properly. The popup does not open up as expected. I am looking to display react select in a modal dialog box. import MenuItem from "@mui/material/MenuItem" ...

React is not displaying the most recent value

During the initial rendering, I start with an empty array for the object date. After trying to retrieve data from an influxDB, React does not re-render to reflect the obtained results. The get function is being called within the useEffect hook (as shown in ...

I tried implementing enums in my Angular Material select component, but unfortunately, it seems to be malfunctioning

Here is my TypeScript file I am working on creating a select list with enums in my project, but I am encountering an error. I have shared screenshots showing the enums with both keys and values, but I only want to display their keys and save their values ...

Enabling Angular Elements to handle non-string properties and inputs

When working with Angular Elements, inputs can be supplied through HTML attributes like so: <some-custom-element someArg="test value"><some-custom-element> An alternative method is utilizing setAttribute. However, it's important to note ...