real initial commit

This commit is contained in:
2025-10-27 13:39:29 -04:00
commit 00cc9eab09
39 changed files with 8605 additions and 0 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+3
View File
@@ -0,0 +1,3 @@
<div class="container">
<open-map [options]="mapOptions" (mapReady)="onMapReady($event)"></open-map>
</div>
+4
View File
@@ -0,0 +1,4 @@
.container {
width: 100%;
height: 95vh;
}
@@ -0,0 +1,29 @@
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have the 'demo' title`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('demo');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Hello, demo');
});
});
+25
View File
@@ -0,0 +1,25 @@
import { Component } from '@angular/core';
import {OpenMapComponent, MapFacade, OpenMapOptions} from 'ngx-open-map-wrapper';
@Component({
selector: 'app-root',
imports: [
OpenMapComponent
],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})
export class AppComponent {
mapOptions: OpenMapOptions = {
forceRaster: false,
styleUrl: "https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",
tileUrl: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
center: [50.426606229502525, 30.56308375468811],
zoom: 16
};
onMapReady(mapFacade: MapFacade) {
console.log(mapFacade);
mapFacade.addMarker([50.426606229502525, 30.56308375468811]);
}
}
@@ -0,0 +1,11 @@
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { appConfig } from './app.config';
const serverConfig: ApplicationConfig = {
providers: [
provideServerRendering(),
]
};
export const config = mergeApplicationConfig(appConfig, serverConfig);
+10
View File
@@ -0,0 +1,10 @@
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideClientHydration, withEventReplay } from '@angular/platform-browser';
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideClientHydration(withEventReplay())
]
};
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Demo</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
+7
View File
@@ -0,0 +1,7 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { config } from './app/app.config.server';
const bootstrap = () => bootstrapApplication(AppComponent, config);
export default bootstrap;
+6
View File
@@ -0,0 +1,6 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));
+67
View File
@@ -0,0 +1,67 @@
import { APP_BASE_HREF } from '@angular/common';
import { CommonEngine, isMainModule } from '@angular/ssr/node';
import express from 'express';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import bootstrap from './main.server';
const serverDistFolder = dirname(fileURLToPath(import.meta.url));
const browserDistFolder = resolve(serverDistFolder, '../browser');
const indexHtml = join(serverDistFolder, 'index.server.html');
const app = express();
const commonEngine = new CommonEngine();
/**
* Example Express Rest API endpoints can be defined here.
* Uncomment and define endpoints as necessary.
*
* Example:
* ```ts
* app.get('/api/**', (req, res) => {
* // Handle API request
* });
* ```
*/
/**
* Serve static files from /browser
*/
app.get(
'**',
express.static(browserDistFolder, {
maxAge: '1y',
index: 'index.html'
}),
);
/**
* Handle all other requests by rendering the Angular application.
*/
app.get('**', (req, res, next) => {
const { protocol, originalUrl, baseUrl, headers } = req;
commonEngine
.render({
bootstrap,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: browserDistFolder,
providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
})
.then((html) => res.send(html))
.catch((err) => next(err));
});
/**
* Start the server if this module is the main entry point.
* The server listens on the port defined by the `PORT` environment variable, or defaults to 4000.
*/
if (isMainModule(import.meta.url)) {
const port = process.env['PORT'] || 4000;
app.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
export default app;
+4
View File
@@ -0,0 +1,4 @@
/* You can add global styles to this file, and also import other style files */
@import "leaflet/dist/leaflet.css";
@import "maplibre-gl/dist/maplibre-gl.css";
+19
View File
@@ -0,0 +1,19 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "../../out-tsc/app",
"types": [
"node"
]
},
"files": [
"src/main.ts",
"src/main.server.ts",
"src/server.ts"
],
"include": [
"src/**/*.d.ts"
]
}
+15
View File
@@ -0,0 +1,15 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "../../out-tsc/spec",
"types": [
"jasmine"
]
},
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}
+120
View File
@@ -0,0 +1,120 @@
# ngx-open-map-wrapper
An Angular 16+ library that provides a **unified map component** with automatic fallback between **MapLibre GL** (WebGL vector maps) and **Leaflet** (raster maps).
It automatically chooses the best renderer for the users device:
- **MapLibre GL** if WebGL is supported
- **Leaflet** if WebGL is not available or raster rendering is forced
---
## ✨ Features
- 🗺️ Always shows a map — automatically picks the right engine for the device
- ⚡ Uses **MapLibre GL** for modern devices with WebGL support
- 🪶 Falls back to **Leaflet** for older or lowend devices
- 🎯 Unified API for markers, zoom, and center — no need to learn two libraries
- 📱 Works seamlessly across desktop and mobile
- 🧩 Angularnative: standalone components, signals, and modern syntax
---
## 📦 Installation
Install the library and its peer dependencies:
```bash
yarn add ngx-open-open-map-wrapper leaflet maplibre-gl
```
Then import the required CSS styles in your global `styles.css` (or `styles.scss`):
```css
@import "leaflet/dist/leaflet.css";
@import "maplibre-gl/dist/maplibre-gl.css";
```
---
## 🚀 Usage
### Import the component
Since the library is **standaloneready**, you can import the component directly:
```ts
import { Component } from '@angular/core';
import { MapComponent, MapFacade } from 'ngx-open-open-map-wrapper';
@Component({
selector: 'app-root',
standalone: true,
imports: [MapComponent],
template: `
<open-map
[center]="[46.3385, -72.6106]"
[zoom]="14"
(mapReady)="onMapReady($event)"
></open-map>
`,
})
export class AppComponent {
private map?: MapFacade;
onMapReady(facade: MapFacade) {
this.map = facade;
this.map.addMarker([46.3385, -72.6106], { color: 'blue' });
}
}
```
---
## ⚙️ API
### `MapComponent` Inputs
- `center: [lat, lng]` → Initial map center
- `zoom: number` → Initial zoom level
- `forceRaster: boolean` → Force Leaflet raster mode even if WebGL is available
- `styleUrl: string` → MapLibre style URL (default: MapLibre basic style)
### `MapComponent` Outputs
- `(mapReady: MapFacade)` → Emits the `MapFacade` instance once the map is initialized
---
### `MapFacade` Methods
- `setCenter([lat, lng])` → Move the map center
- `setZoom(zoom: number)` → Set zoom level
- `addMarker([lat, lng], { color?: string })` → Add a marker
- `destroy()` → Clean up map instance
---
## 🧩 WebGL Detection Directive
You can also use the directive directly if you want to check WebGL support:
```html
<div webglDetection (webglSupport)="onWebGLCheck($event)">
@if (webglOk) {
<my-component-using-webgl></my-component-using-webgl>
} @else {
<p>WebGL not supported → fallback</p>
}
</div>
```
```ts
webglOk = false;
onWebGLCheck(supported: boolean) {
this.webglOk = supported;
}
```
---
## 📜 License
MIT
@@ -0,0 +1,7 @@
{
"$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
"dest": "../../dist/ngx-open-map-wrapper",
"lib": {
"entryFile": "src/public-api.ts"
}
}
@@ -0,0 +1,29 @@
{
"name": "@svrnty/ngx-open-map-wrapper",
"version": "0.2.1",
"keywords": [
"maplibre",
"leaflet",
"maps",
"open source",
"angular",
"ngx"
],
"author": "Svrnty",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://git.openharbor.io/svrnty/ngx-open-map-wrapper"
},
"publishConfig": { "access": "public" },
"peerDependencies": {
"@angular/common": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"@angular/core": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"maplibre-gl": "^5.0.0",
"leaflet": "^1.0.0 || ^2.0.0"
},
"dependencies": {
"tslib": "^2.3.0"
},
"sideEffects": false
}
@@ -0,0 +1,40 @@
import {
Map,
TileLayer,
Marker,
} from 'leaflet';
import {
IMapAdapter,
LatLng,
MapOptions,
} from './map-adapter.interface';
export class LeafletAdapter implements IMapAdapter {
private map!: Map;
init(container: HTMLElement, options: MapOptions): void {
this.map = new Map(container).setView(options.center, options.zoom);
new TileLayer(options.tileUrl, {
attribution: '&copy; OpenStreetMap contributors',
}).addTo(this.map);
}
setCenter(latLng: LatLng): void {
this.map.setView(latLng, this.map.getZoom());
}
setZoom(zoom: number): void {
this.map.setZoom(zoom);
}
addMarker(latLng: LatLng, options?: { color?: string }): void {
const marker = new Marker(latLng);
marker.addTo(this.map);
}
destroy(): void {
this.map.remove();
}
}
@@ -0,0 +1,35 @@
import { Map, Marker, NavigationControl } from 'maplibre-gl';
import {getLngLat, IMapAdapter, LatLng, MapOptions} from './map-adapter.interface';
export class LibreAdapter implements IMapAdapter {
private map!: Map;
init(container: HTMLElement, options: MapOptions): void {
this.map = new Map({
container,
style: options.styleUrl!,
center: getLngLat(options.center),
zoom: options.zoom,
});
this.map.addControl(new NavigationControl(), 'top-right');
}
setCenter(latLng: LatLng): void {
this.map.setCenter(getLngLat(latLng));
}
setZoom(zoom: number): void {
this.map.setZoom(zoom);
}
addMarker(latLng: LatLng, options?: { color?: string }): void {
new Marker({ color: options?.color || 'red' })
.setLngLat(getLngLat(latLng))
.addTo(this.map);
}
destroy(): void {
this.map.remove();
}
}
@@ -0,0 +1,20 @@
export interface MapOptions {
center: LatLng;
zoom: number;
styleUrl: string;
tileUrl: string;
}
export type LatLng = [number, number];
export function getLngLat(latLng: LatLng): [number, number] {
return [latLng[1], latLng[0]];
}
export interface IMapAdapter {
init(container: HTMLElement, options: MapOptions): void;
setCenter(latLng: LatLng): void;
setZoom(zoom: number): void;
addMarker(latLng: LatLng, options?: { color?: string }): void;
destroy(): void;
}
@@ -0,0 +1,40 @@
import { IMapAdapter, MapOptions, LatLng } from './map-adapter.interface';
import { LibreAdapter } from './libre-adapter';
import { LeafletAdapter } from './leaflet-adapter';
export class MapFacade implements IMapAdapter {
private readonly adapter: IMapAdapter;
private readonly leafletZoomOffset = 1;
constructor(forceRaster: boolean, webglAvailable: boolean) {
if (forceRaster || !webglAvailable) {
this.adapter = new LeafletAdapter();
} else {
this.adapter = new LibreAdapter();
}
}
init(container: HTMLElement, options: MapOptions): void {
if (this.adapter instanceof LeafletAdapter)
options.zoom += this.leafletZoomOffset;
this.adapter.init(container, options);
}
setCenter(latLng: LatLng): void {
this.adapter.setCenter(latLng);
}
setZoom(zoom: number): void {
if (this.adapter instanceof LeafletAdapter)
zoom += this.leafletZoomOffset;
this.adapter.setZoom(zoom);
}
addMarker(latLng: LatLng, options?: { color?: string }): void {
this.adapter.addMarker(latLng, options);
}
destroy(): void {
this.adapter.destroy();
}
}
@@ -0,0 +1,4 @@
.map-container {
width: 100%;
height: 100%;
}
@@ -0,0 +1,3 @@
<div #mapContainer class="map-container" webglDetection (webglSupport)="webglDetection($event)">
</div>
@@ -0,0 +1,76 @@
import {
AfterViewInit,
Component,
effect,
ElementRef,
inject, Injector,
input,
output,
PLATFORM_ID, runInInjectionContext,
ViewChild
} from '@angular/core';
import {isPlatformBrowser} from '@angular/common';
import {MapOptions} from '../../adapters/map-adapter.interface';
import {MapFacade} from '../../adapters/map-facade';
import {WebglDetectionDirective} from '../../directives/webgl-detection.directive';
export interface OpenMapOptions extends MapOptions {
forceRaster: boolean;
}
@Component({
selector: 'open-map',
imports: [
WebglDetectionDirective
],
templateUrl: './open-map.component.html',
styleUrl: './open-map.component.css',
standalone: true,
})
export class OpenMapComponent implements AfterViewInit {
private readonly platformId = inject(PLATFORM_ID);
private readonly injector = inject(Injector);
webglSupported?: boolean;
map?: MapFacade;
@ViewChild('mapContainer', { static: true }) mapContainer!: ElementRef<HTMLDivElement>;
options = input<OpenMapOptions>({
center: [50.426606229502525, 30.56308375468811],
zoom: 6,
styleUrl: 'https://basemaps.cartocdn.com/gl/positron-gl-style/style.json',
tileUrl: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
forceRaster: false,
});
mapReady = output<MapFacade>();
ngAfterViewInit(): void {
if (false === isPlatformBrowser(this.platformId))
return;
runInInjectionContext(this.injector, () => {
effect(() => {
if (undefined === this.webglSupported)
return;
if (!this.map)
this.initializeMap();
});
});
}
webglDetection(supported: boolean): void {
this.webglSupported = supported;
if (undefined === this.map)
this.initializeMap();
}
private initializeMap(): void {
const options = this.options();
this.map = new MapFacade(options.forceRaster, this.webglSupported!);
this.map.init(this.mapContainer.nativeElement, options);
this.mapReady.emit(this.map);
}
}
@@ -0,0 +1,48 @@
import {
Directive,
inject,
OnInit, output,
PLATFORM_ID
} from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
@Directive({
selector: '[webglDetection]',
standalone: true
})
export class WebglDetectionDirective implements OnInit {
private readonly platformId = inject(PLATFORM_ID);
webglSupport = output<boolean>();
ngOnInit(): void {
if (!isPlatformBrowser(this.platformId))
return;
const supported = this.checkWebGLSupport();
this.webglSupport.emit(supported);
}
private checkWebGLSupport(): boolean {
let canvas: HTMLCanvasElement | undefined = undefined;
try {
canvas = document.createElement('canvas');
const gl = (
canvas.getContext('webgl') ||
canvas.getContext('experimental-webgl')
) as WebGLRenderingContext | null;
const supported =
!!window.WebGLRenderingContext &&
!!(gl);
return supported;
} catch {
return false;
}
finally {
canvas?.remove();
}
}
}
@@ -0,0 +1,11 @@
/*
* Public API Surface of ngx-open-open-map-wrapper
*/
// Interfaces & types
export * from './lib/adapters/map-adapter.interface';
export * from './lib/adapters/map-facade';
// Angular components & directives
export * from './lib/components/open-map/open-map.component';
export * from './lib/directives/webgl-detection.directive';
@@ -0,0 +1,15 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "../../out-tsc/lib",
"declaration": true,
"declarationMap": true,
"inlineSources": true,
"types": []
},
"exclude": [
"**/*.spec.ts"
]
}
@@ -0,0 +1,11 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"extends": "./tsconfig.lib.json",
"compilerOptions": {
"declarationMap": false
},
"angularCompilerOptions": {
"compilationMode": "partial"
}
}
@@ -0,0 +1,15 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "../../out-tsc/spec",
"types": [
"jasmine"
]
},
"include": [
"**/*.spec.ts",
"**/*.d.ts"
]
}