Utilize Angular 6 to Enhance Open Street Maps by Adding a Custom Marker to the Map

After reading through this article, I have successfully developed an OSM layer component. My next goal is to incorporate a pin or marker for a specific geo-location. Has anyone else achieved this task before?

Answer №1

Develop a custom component named "map".
map.component.html:

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

map.component.ts:

import { Component, OnInit } from '@angular/core';

declare var ol: any;

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css']
})
export class PrincipalComponent implements OnInit {

  constructor() { }

  latitude: number = -16.509418;
  longitude: number = -68.124151;

  ngOnInit() {
    this.map = new ol.Map({
      target: 'map',
      layers: [
        new ol.layer.Tile({
          source: new ol.source.OSM()
        })
      ],
      view: new ol.View({
        center: ol.proj.fromLonLat([this.longitude, this.latitude]),
        zoom: 12
      })
    });
    this.addPoint(this.latitude, this.longitude);
  }

  setCenter() {
    var view = this.map.getView();
    view.setCenter(ol.proj.fromLonLat([this.longitude, this.latitude]));
    view.addMarker(ol.proj.fromLonLat([this.longitude, this.latitude]));
    view.setZoom(12);
  }

  addPoint(lat: number, lng: number) {
    var vectorLayer = new ol.layer.Vector({
      source: new ol.source.Vector({
        features: [new ol.Feature({
          geometry: new ol.geom.Point(ol.proj.transform([lng, lat], 'EPSG:4326', 'EPSG:3857')),
        })]
      }),
      style: new ol.style.Style({
        image: new ol.style.Icon({
          anchor: [0.5, 0.5],
          anchorXUnits: "fraction",
          anchorYUnits: "fraction",
          src: "assets/img/my-icon.png"
        })
      })
    });
    this.map.addLayer(vectorLayer);
    }
}

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

Incorporating ng2-bootstrap into an Angular2 project with SystemJS starter template

I am attempting to integrate the ng2-bootstrap modal functionality into a component of my project that is built using the angular2-starter. Below is my systemjs.conf.js configuration: /* * This config is only used during development and build phase onl ...

What prevents me from extending an Express Request Type?

My current code looks like this: import { Request, Response, NextFunction } from 'express'; interface IUserRequest extends Request { user: User; } async use(req: IUserRequest, res: Response, next: NextFunction) { const apiKey: string = ...

Error encountered: Type 'IPromise<{}>' is not compatible with type 'IPromise<IWebErrors[]>'. This issue arose during the migration from Typescript version 1.8 to 2.5

Can someone please help me troubleshoot this code? I've tried adding .topromise() and using a then, but it's not solving the issue. getWebErrors(): ng.IPromise<Array<IWebErrors>> { var defer = this.q.defer(); this.h ...

How can I prevent node_module from being included when using the include directive in tsconfig.json?

Many developers are excluding the node_modules folder in their tsconfig.json. I, on the other hand, am using the include directive with specific folder patterns. Do I really need to exclude node_modules? And what about third-party libraries that aren' ...

Backend not receiving the request

While all tests pass successfully in Postman, I'm encountering an issue where requests are not reaching the backend when testing from the front-end. import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common ...

Executing an asynchronous function within a TypeScript decorator

Apologies in advance for the lengthy question. I am striving to provide a clear explanation of the issue I am currently encountering. During the development of my decorators utilities library, I came across an unexpected behavior while working on one spec ...

I'm having trouble locating a declaration file for the module 'vue-prism-component'

Currently utilizing Vue 3 (Composition API), Vite, and Typescript but encountering a missing module issue with vue-prism-component. <script lang="ts" setup> import 'prismjs' import 'prismjs/themes/prism-tomorrow.css' imp ...

How can I extract an array of objects from a response in Angular?

Arrange array of objects from the received data. Here is the data that I received. [ {name:someName, value:20}, {name:"", value:21} {name:someName, value:25} {name:someName , value:27} {name:"", value:21} {name:someName, value:20} ] I am looki ...

Changing Angular code to vanilla JavaScript

Here is an example code snippet for a plugin used in an Ionic/Capacitor/Angular project: import { ForegroundService } from '@awesome-cordova-plugins/foreground-service/ngx'; constructor(public foregroundService: ForegroundService) { } ... sta ...

Using solely the directory to import index.ts

When attempting to import a module called index.ts from a directory by only specifying the directory name and not the module name itself, I encountered a TS2307 error stating "Cannot find module". Here is a snippet from ./src/main.ts: 'use strict&ap ...

Implementing SSL CA Bundle in NodeJS 14

Currently, I am in the process of integrating a CA Bundle with NodeJS 14.0. I found instructions on Namecheap's website that have been helpful thus far, but I need some further clarification on a couple of points: What file formats are accepted for t ...

What is the functionality of mergeMap in handling errors?

In our unique scenario, we are dealing with a specific use case where we need to load 200 images 10 at a time. Utilizing MergeMap with concurrency in rxjs seems like the ideal approach for handling 200 HTTP requests and executing them in batches of 10. How ...

Windows drive letter casing error when using Yarn and NextJS

Today, I set up a fresh project using Yarn and NextJS on my Windows computer. When I try to start the project, I encounter an error stating that the casing is "invalid" for the project directory. The specific errors I am facing are: Invalid casing detecte ...

Angular version 12 (node:3224) UnhandledPromiseRejectionWarning: Issue encountered with mapping:

Trying to generate the translation file in my Angular project using the command ng extract-i18n --output-path src/translate, I encountered this error message: \ Generating browser application bundles (phase: building)...(node:3224) UnhandledPromiseRej ...

Proper method for typing the generics of DatePickerProps belonging to the DatePicker component in mui-x library

I have a component called CustomDatePicker which has been configured for localization as shown below: function CustomDatePicker(props: DatePickerProps<unknown> & React.RefAttributes<HTMLDivElement>) { return ( <StyledDatePicker ...

What is the reason behind typescript not needing `undefined` with the ?: operator on arrays?

type Artifact = { a:string } const items : Artifact[] = []; // this will result in a syntax error let z?: Artifact; // assigning undefined to a variable of type Artifact is an error const b : Artifact = undefined; // despite expectations, this assi ...

Encountering a challenge when upgrading to eslint version 9.0.0

Encountering an issue while trying to upgrade eslint to version 9.0.0. ⋊> ~/A/fusion on turborepo ⨯ bun lint 22:21:58 $ eslint packages/*/src/**/* Oops! Something went wrong! :( ESLint: 9.0. ...

Creating a Timestamp in JavaScript: A step-by-step guide

I have data from a Firebase database that requires processing before being returned in the same format. The Date of Birth field is retrieved in a Timestamp format, which I convert to a date, process, and then revert back to a timestamp using the code snipp ...

Only one choice for discriminated unions in react props

Looking to create a typescript type for react component props, specifically a basic button that can accept either an icon prop or a text prop, but not both. My initial attempt with a discriminated union didn't quite produce the desired outcome: inter ...

Make changes to an array in Javascript without altering the original array

I currently have an array : let originalArr = ['apple', 'plum', 'berry']; Is there a way to eliminate the item "plum" from this array without altering the originalArr? One possible solution could be: let copyArr = [...origin ...