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

I encountered a TypeError when attempting to load MDX in Next.js with the mdx-js/react library

My Goals and Assumptions for the Project Please note that this question has been translated using Deepl Translations. I aim to integrate mdx-js/react into Next.js for loading mdx files. Environment Details: Operating System: macOS Big Sur Node Version: ...

Tips for creating React/MobX components that can be reused

After seeing tightly coupled examples of integrating React components with MobX stores, I am seeking a more reusable approach. Understanding the "right" way to achieve this would be greatly appreciated. To illustrate my goal and the challenge I'm fac ...

Having trouble with AWS, Angular, and Docker integration issues

I have successfully dockerized my Angular app using the following Dockerfile: FROM node:8.9 as node WORKDIR /app COPY package.json /app/ RUN npm install COPY ./ /app/ ARG env=prod RUN npm run build -- --prod --environment $env FROM nginx:1.13 COPY -- ...

Deno.Command uses backslashes instead of quotes for input containment

await new Deno.Command('cmd', { args: [ '/c', 'start', `https://accounts.spotify.com/authorize?${new URLSearchParams({ client_id, response_type: 'code', ...

How Angular Router deals with "/" in a route parameter

I've been working on an Angular project with routing, focusing on a route structure like the one below. { path : 'preview/:Id', loadChildren : () => import('./path/preview/preview.module').then( m => m.Preview ...

Error: In Angular and Typescript, the function this.$resource is not recognized

I keep encountering a TypeError: this.$resource is not a function. Below is the code snippet causing the issue: export class DataAccessService implements IDataAccessService { static $inject = ["$resource"]; constructor(private $resource: ng ...

Data can be retrieved in a React/Next.js application when a button is clicked, even if the button is located in a separate

Whenever the button is clicked, my function fetches weather data for the current location. I am trying to figure out how to transfer this data from the Location component to the pages/index.tsx. This is where another component will display the data. This ...

Combining TypeScript into HTML resulted in an error: Uncaught ReferenceError clickbutton is not defined

Attempting to create a basic CRUD frontend without the use of any frameworks. I am encountering an issue when trying to include a TypeScript file (index.ts) in my index.html, as the functions called within it are showing as undefined. I understand that bro ...

What is the best way to implement forwardRef in a distinct select component?

Currently, I am utilizing react, typescript, and styled-components to work on my project. Specifically, I am aiming to create a select component for use in React Hook Form. Initially, everything seemed to be in order, but I encountered an error from typesc ...

Is there a more efficient method for providing hooks to children in React when using TypeScript?

My component structure looks something like this: Modal ModalTitle ModalBody FormElements MySelect MyTextField MyCheckbox DisplayInfo ModalActions I have a state variable called formVars, and a function named handleAction, ...

Encountering build:web failure within npm script due to TypeScript

Our project is utilizing the expo-cli as a local dependency in order to execute build:web from an npm script without requiring the global installation of expo-cli. However, when we run npm run build:web, we encounter the following exception. To isolate th ...

Does Nativescript successfully utilize AOT Compilation even with the `Compiler` package still included?

I'm running this command: npm run ns-bundle --android --build-app --uglify The command is successful (you can find the complete log here). After navigating to the report folder (generated by webpack-bundle-size-analyzer), I found these two files: ...

Select hours using the PrimeNG slider feature

Is there a way to customize the PrimeNG slider in order to allow for selecting a time interval? I would like the slider to default to 12:00 when the user opens the application, but also be able to extend the selection range from 00:00 to 23:59. It seems ...

Encountering difficulties while configuring an Angular project on my local machine from GitLab (unable to install npm locally)

There are deprecated warnings for certain npm packages in the Node.js environment. It is advised to upgrade to specific versions to avoid ReDos regression issues: [email protected]: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 [email  ...

Having trouble with the backbutton override in Angular 7 and Cordova 8?

I'm creating a mobile app using Angular 7 and Cordova 8. I need to prevent the default behavior of the back button in order to stop the app from closing. Following instructions in the Cordova documentation, I added an event listener to override the ba ...

Limit the types of components allowed as children in a React component by utilizing TypeScript

I've been struggling with this question for a while, searching through answers but still unable to get my code to work. Here's the issue at hand. Within my code, I have a component called Steps which acts as a wrapper. I also have multiple Step ...

Volar and vue-tsc are producing conflicting TypeScript error messages

During the development of my project using Vite, Vue 3, and TypeScript, I have set up vue-tsc to run in watch mode. I am utilizing VS Code along with Volar. This setup has been helpful as it displays all TypeScript errors in the console as expected, but I ...

Create a typescript class object

My journey with Typescript is just beginning as I delve into using it alongside Ionic. Coming from a background in Java, I'm finding the syntax and approach quite different and challenging. One area that's giving me trouble is creating new object ...

Creating a customizable filter by using the function of an object

I am currently developing a customizable dynamic filter system, similar to the functionalities offered by Yahoo Screener. To achieve this, I have defined an interface for the available filter fields: export interface FilterField { label: string; se ...

Angular 6 - Ensuring all child components are instances of the same component

My issue has been simplified: <div *ngIf="layout1" class="layout1"> <div class="sidebar-layout1"> some items </div> <child-component [something]="sth"></child-component> </div> <div *ngIf="!layout1" class= ...