Merge branch 'feature/main'

# Conflicts:
#	package-lock.json
#	package.json
This commit is contained in:
David Nguyen 2025-11-05 15:59:22 -05:00
commit 7551c0f26c
Signed by: david.nguyen
GPG Key ID: D5FB5A5715829326
39 changed files with 24149 additions and 90 deletions

17
.editorconfig Normal file
View File

@ -0,0 +1,17 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
ij_typescript_use_double_quotes = false
[*.md]
max_line_length = off
trim_trailing_whitespace = false

44
.gitignore vendored Normal file
View File

@ -0,0 +1,44 @@
# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db

4
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,4 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
"recommendations": ["angular.ng-template"]
}

20
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,20 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "ng serve",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: start",
"url": "http://localhost:4200/"
},
{
"name": "ng test",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: test",
"url": "http://localhost:9876/debug.html"
}
]
}

42
.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,42 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "start",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
},
{
"type": "npm",
"script": "test",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
}
]
}

140
angular.json Normal file
View File

@ -0,0 +1,140 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"ngx-open-map-wrapper": {
"projectType": "library",
"root": "projects/ngx-open-map-wrapper",
"sourceRoot": "projects/ngx-open-map-wrapper/src",
"prefix": "lib",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:ng-packagr",
"options": {
"project": "projects/ngx-open-map-wrapper/ng-package.json"
},
"configurations": {
"production": {
"tsConfig": "projects/ngx-open-map-wrapper/tsconfig.lib.prod.json"
},
"development": {
"tsConfig": "projects/ngx-open-map-wrapper/tsconfig.lib.json"
}
},
"defaultConfiguration": "production"
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"tsConfig": "projects/ngx-open-map-wrapper/tsconfig.spec.json",
"polyfills": [
"zone.js",
"zone.js/testing"
]
}
}
}
},
"demo": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "projects/demo",
"sourceRoot": "projects/demo/src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/demo",
"index": "projects/demo/src/index.html",
"browser": "projects/demo/src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "projects/demo/tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
{
"glob": "**/*",
"input": "projects/demo/public"
}
],
"styles": [
"projects/demo/src/styles.scss"
],
"scripts": [],
"server": "projects/demo/src/main.server.ts",
"prerender": true,
"ssr": {
"entry": "projects/demo/src/server.ts"
}
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kB",
"maximumError": "1MB"
},
{
"type": "anyComponentStyle",
"maximumWarning": "4kB",
"maximumError": "8kB"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "demo:build:production"
},
"development": {
"buildTarget": "demo:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n"
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": [
"zone.js",
"zone.js/testing"
],
"tsConfig": "projects/demo/tsconfig.spec.json",
"inlineStyleLanguage": "scss",
"assets": [
{
"glob": "**/*",
"input": "projects/demo/public"
}
],
"styles": [
"projects/demo/src/styles.scss"
],
"scripts": []
}
}
}
}
}
}

15341
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,38 +1,52 @@
{
"name": "@svrnty/ngx-open-map-wrapper",
"version": "0.2.2",
"keywords": [
"maplibre",
"leaflet",
"maps",
"open source",
"angular",
"ngx"
],
"author": "Svrnty",
"license": "MIT",
"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"
"name": "ngx-open-map-wrapper",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"serve:ssr:demo": "node dist/demo/server/server.mjs"
},
"private": true,
"dependencies": {
"tslib": "^2.3.0"
"@angular/common": "^19.2.0",
"@angular/compiler": "^19.2.0",
"@angular/core": "^19.2.0",
"@angular/forms": "^19.2.0",
"@angular/platform-browser": "^19.2.0",
"@angular/platform-browser-dynamic": "^19.2.0",
"@angular/platform-server": "^19.2.0",
"@angular/router": "^19.2.0",
"@angular/ssr": "^19.2.15",
"@maplibre/maplibre-gl-directions": "^0.8.0",
"@svrnty/ngx-open-map-wrapper": "file:../ngx-open-map-wrapper/dist/ngx-open-map-wrapper",
"express": "^4.18.2",
"leaflet": "^2.0.0-alpha.1",
"leaflet-routing-machine": "^3.2.12",
"maplibre-gl": "^5.7.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.15.0"
},
"sideEffects": false,
"module": "fesm2022/svrnty-ngx-open-map-wrapper.mjs",
"typings": "index.d.ts",
"exports": {
"./package.json": {
"default": "./package.json"
},
".": {
"types": "./index.d.ts",
"default": "./fesm2022/svrnty-ngx-open-map-wrapper.mjs"
}
}
"devDependencies": {
"@angular-devkit/build-angular": "^19.2.15",
"@angular/cli": "^19.2.12",
"@angular/compiler-cli": "^19.2.0",
"@types/express": "^4.17.17",
"@types/jasmine": "~5.1.0",
"@types/leaflet": "^1.9.20",
"@types/leaflet-routing-machine": "^3.2.9",
"@types/node": "^18.18.0",
"jasmine-core": "~5.6.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"ng-packagr": "^19.2.0",
"typescript": "~5.7.2"
},
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1,3 @@
<div class="container">
<open-map [options]="mapOptions" (mapReady)="onMapReady($event)"></open-map>
</div>

View File

@ -0,0 +1,4 @@
.container {
width: 100%;
height: 95vh;
}

View File

@ -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');
});
});

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]);
}
}

View File

@ -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);

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())
]
};

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>

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;

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));

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;

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";

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"
]
}

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"
]
}

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

View File

@ -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"
}
}

View File

@ -0,0 +1,31 @@
{
"name": "@svrnty/ngx-open-map-wrapper",
"version": "0.2.2",
"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",
"leaflet-routing-machine": "^3.0.0",
"@maplibre/maplibre-gl-directions": "^0.8.0"
},
"dependencies": {
"tslib": "^2.3.0"
},
"sideEffects": false
}

View File

@ -0,0 +1,235 @@
import L,{
Map,
TileLayer,
Marker,
Popup,
polygon, DivIcon
} from 'leaflet';
import 'leaflet-routing-machine';
import {
getLngLat,
IMapAdapter,
LatLng,
MapOptions,
Zone,
RouteOptions,
} from './map-adapter.interface';
export class LeafletAdapter implements IMapAdapter<Marker> {
private map!: Map;
private markers: Record<string, Marker> = {};
private popup?: Popup;
private routes: Record<string, any> = {};
private polygons: Record<number, L.Polygon> = {};
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?: { id?: string; color?: string ; icon? : DivIcon }) {
if (!options?.id) {
console.warn('addMarker called without id, marker will not be tracked');
return;
}
const markerOptions: L.MarkerOptions = {};
if (options?.icon) {
markerOptions.icon = options.icon;
}
if (this.markers[options.id]) {
this.map.removeLayer(this.markers[options.id]);
}
const marker = new Marker(latLng, markerOptions);
marker.addTo(this.map);
this.markers[options.id] = marker;
}
getMarker(id: string): Marker | undefined {
return this.markers[id];
}
getAllMarkers(): Record<string, Marker> {
return this.markers;
}
removeMarker(id?: string): void {
if (!id) {
console.warn('removeMarker called without id');
return;
}
if (this.markers[id]) {
this.map.removeLayer(this.markers[id]);
delete this.markers[id];
}
}
hasMarker(id: string): boolean {
return !!this.markers[id];
}
updateMarkerIcon(id: string, icon: any): void {
const marker = this.markers[id];
if (marker) {
marker.setIcon(icon);
}
}
updateMarkerPopup(id: string, content: HTMLElement): void {
const marker = this.markers[id];
if (marker) {
const popup = L.popup({
offset: [-5, -30],
}).setContent(content);
marker.bindPopup(popup);
}
}
addMarkerClickHandler(id: string, handler: (e: any) => void): void {
const marker = this.markers[id];
if (marker) {
marker.on('click', handler);
}
}
addZone(zones: Zone[]): void
{
this.updateZone(zones);
}
updateZone(zones: Zone[]): void
{
for(let zone of zones)
{
// Remove old polygon if it exists
if (this.polygons[zone.id]) {
this.map.removeLayer(this.polygons[zone.id]);
}
const latlngs = zone.polygon.map((geoPoint) => {
return [geoPoint.x, geoPoint.y] as LatLng;
});
let color = "#ff0000"
let opacity = 0.4;
if(zone.color)
color = zone.color;
if (zone.opacity)
opacity = zone.opacity;
const poly = polygon(latlngs, { color, fillOpacity: opacity })
.addTo(this.map);
// Store polygon reference for later removal/update
this.polygons[zone.id] = poly;
}
}
openZonePopup(zone: Zone) : void
{
let sumLat = 0;
let sumLng = 0;
zone.polygon.forEach(point => {
sumLat += point.x;
sumLng += point.y;
});
const centerLat = sumLat / zone.polygon.length;
const centerLng = sumLng / zone.polygon.length;
if (this.popup) {
this.map.closePopup(this.popup);
}
this.popup = new Popup()
.setLatLng([centerLat, centerLng])
.setContent(`
<div >
${zone.name ? `<p><strong>${zone.name}</strong></p>` : ''}
${zone.shippingFee ? `<p>Shipping: ${zone.shippingFee}</p>` : ''}
${zone.shippingScheduleStart ? `<p>Delivery: ${zone.shippingScheduleStart}</p>` : ''}
${zone.shippingScheduleEnd? `<p>Delivery: ${zone.shippingScheduleEnd}</p>` : ''}
</div>`)
.openOn(this.map);
}
closePopup(): void
{
if (this.popup) {
this.map.closePopup(this.popup);
this.popup = undefined;
}
}
addRoute(id: string, waypoints: LatLng[], options?: RouteOptions): void {
this.removeRoute(id);
const routeOptions: any = {
waypoints: waypoints.map(wp => L.latLng(wp[0], wp[1])),
lineOptions: {
styles: [
{
color: options?.lineStyle?.color || '#3388ff',
opacity: options?.lineStyle?.opacity ?? 1,
weight: options?.lineStyle?.weight || 4
}
],
extendToWaypoints: false,
addWaypoints: false,
missingRouteTolerance: 10
},
createMarker: options?.showMarkers ? undefined : () => false,
draggableWaypoints: options?.draggableWaypoints ?? false,
routeWhileDragging: false,
summaryTemplate: '',
distanceTemplate: '',
timeTemplate: '',
show: true
};
if (options?.serviceUrl) {
routeOptions.router = L.Routing.osrmv1({
serviceUrl: options.serviceUrl
});
}
const control = L.Routing
.control(routeOptions)
.addTo(this.map);
this.routes[id] = control;
}
updateRoute(id: string, waypoints: LatLng[], options?: RouteOptions): void {
this.addRoute(id, waypoints, options);
}
removeRoute(id: string): void {
if (this.routes[id]) {
this.routes[id].remove();
delete this.routes[id];
}
}
removeAllRoutes(): void {
Object.keys(this.routes).forEach(id => this.removeRoute(id));
}
on(type: string, event: (e: any) => void): void
{
this.map.on(type, event);
}
destroy(): void {
this.removeAllRoutes();
// Clean up polygons
Object.values(this.polygons).forEach(poly => this.map.removeLayer(poly));
this.map.remove();
}
}

View File

@ -0,0 +1,334 @@
import { Map, Marker, NavigationControl, GeoJSONSource, Popup } from 'maplibre-gl';
import {getLngLat, IMapAdapter, LatLng, MapOptions, Zone, RouteOptions} from './map-adapter.interface';
import MapLibreGlDirections from "@maplibre/maplibre-gl-directions";
export class LibreAdapter implements IMapAdapter<Marker> {
private map!: Map;
private markers: Record<string, Marker> = {};
private markerClickHandlers: Record<string, (e: any) => void> = {};
private popup?: Popup;
private directions: Record<string, MapLibreGlDirections> = {};
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?: { id?: string; color?: string; icon?: HTMLElement }) {
if (!options?.id) {
console.warn('addMarker called without id, marker will not be tracked');
return;
}
const coords = getLngLat(latLng);
const markerOptions: any = {};
if (options?.icon) {
markerOptions.element = options.icon;
} else if (options?.color) {
markerOptions.color = options.color;
} else {
markerOptions.color = 'red';
}
if (this.markers[options.id]) {
this.markers[options.id].remove();
}
const marker = new Marker(markerOptions)
.setLngLat(coords)
.addTo(this.map);
this.markers[options.id] = marker;
}
getMarker(id: string): Marker | undefined {
return this.markers[id];
}
getAllMarkers(): Record<string, Marker> {
return this.markers;
}
removeMarker(id?: string): void {
if (!id) {
console.warn('removeMarker called without id');
return;
}
if (this.markers[id]) {
this.markers[id].remove();
delete this.markers[id];
// Clean up stored click handler
delete this.markerClickHandlers[id];
}
}
hasMarker(id: string): boolean {
return !!this.markers[id];
}
updateMarkerIcon(id: string, icon: HTMLElement): void {
const marker = this.markers[id];
if (marker) {
this.markers[id] = this.recreateMarker(id, marker, icon);
}
}
updateMarkerPopup(id: string, content: HTMLElement): void {
const marker = this.markers[id];
if (marker) {
// Create MapLibre popup with the HTML content
const popup = new Popup({
offset: [0, -30],
maxWidth: '400px',
className: 'delivery-popup'
}).setDOMContent(content);
marker.setPopup(popup);
}
}
addMarkerClickHandler(id: string, handler: (e: any) => void): void {
const marker = this.markers[id];
if (marker) {
// Store the handler so we can re-apply it when re-adding markers
this.markerClickHandlers[id] = handler;
marker.getElement().addEventListener('click', handler);
}
}
addZone(zones: Zone[]): void
{
this.updateZone(zones);
}
updateZone(zones: Zone[]): void
{ const features = zones.map((zone) => {
const coords = zone.polygon.map((pt) => [pt.y, pt.x]);
if (coords[0][0] !== coords[coords.length - 1][0] || coords[0][1] !== coords[coords.length - 1][1]) {
coords.push(coords[0]);
}
return {
type: 'Feature' as const,
properties: {
id: zone.id,
name: zone.name,
color: zone.color ? zone.color : '#ff0000',
opacity: zone.opacity ? zone.opacity : 0.4,
},
geometry: {
type: 'Polygon' as const,
coordinates: [coords]
},
};
});
const geojson = {
type: 'FeatureCollection' as const,
features,
};
if (this.map.getSource("zones")) {
(this.map.getSource("zones") as GeoJSONSource).setData(geojson);
}
else {
this.map.addSource("zones", {
type: "geojson",
data: geojson,
});
this.map.addLayer({
id: "zones-fill",
type: "fill",
source: "zones",
paint: {
"fill-color": ["get", "color"],
"fill-opacity": ["get", "opacity"],
},
});
this.map.addLayer({
id: "zones-outline",
type: "line",
source: "zones",
paint: {
"line-color": ["get", "color"],
"line-width": 2,
},
});
}
}
openZonePopup(zone: Zone) : void
{
let sumLng = 0;
let sumLat = 0;
zone.polygon.forEach(point => {
sumLng += point.y;
sumLat += point.x;
});
const centerLng = sumLng / zone.polygon.length;
const centerLat = sumLat / zone.polygon.length;
this.closePopup();
this.popup = new Popup({
closeButton: true,
closeOnClick: false,
})
.setLngLat([centerLng, centerLat])
.setHTML(`
<div class="delivery-zone">
${zone.name ? `<p><strong>${zone.name}</strong></p>` : ''}
${zone.shippingFee ? `<p>Shipping: ${zone.shippingFee}$</p>` : ''}
${zone.shippingScheduleStart ? `<p>Delivery: ${zone.shippingScheduleStart}</p>` : ''}
${zone.shippingScheduleEnd? `<p>Delivery: ${zone.shippingScheduleEnd}</p>` : ''}
</div>`)
.addTo(this.map);
}
closePopup(): void
{
if (this.popup) {
this.popup.remove();
this.popup = undefined;
}
}
addRoute(id: string, waypoints: LatLng[], options?: RouteOptions): void {
this.removeRoute(id);
const directionsConfig: any = {
sourceName: `maplibre-gl-directions-${id}`, // Unique source name per route
requestOptions: {
overview: 'full',
}
};
if (options?.serviceUrl) {
let apiUrl = options.serviceUrl;
apiUrl = apiUrl.replace(/\/$/, '');
if (!apiUrl.endsWith('/route/v1')) {
apiUrl = `${apiUrl}/route/v1`;
}
directionsConfig.api = apiUrl;
directionsConfig.profile = options.profile || 'driving';
}
const directions = new MapLibreGlDirections(this.map, directionsConfig);
directions.interactive = false;
const coordinates = waypoints.map(wp => getLngLat(wp));
directions.setWaypoints(coordinates);
this.directions[id] = directions;
if (options?.lineStyle) {
directions.on('fetchroutesend', () => {
this.applyRouteLineStyle(directionsConfig.sourceName, options.lineStyle);
});
}
this.readdAllMarkers();
}
private recreateMarker(id: string, marker: Marker, element?: HTMLElement): Marker {
const lngLat = marker.getLngLat();
const markerElement = element || marker.getElement();
const popup = marker.getPopup();
// Remove old marker
marker.remove();
// Create new marker with updated element
const newMarker = new Marker({ element: markerElement })
.setLngLat(lngLat)
.addTo(this.map);
// Restore popup if exists
if (popup) {
newMarker.setPopup(popup);
}
// Restore click handler if exists
if (this.markerClickHandlers[id]) {
newMarker.getElement().addEventListener('click', this.markerClickHandlers[id]);
}
return newMarker;
}
private applyRouteLineStyle(sourceName: string, lineStyle?: any): void {
if (!lineStyle) return;
const routeLineLayer = `${sourceName}-routeline`;
const routeLineCasingLayer = `${sourceName}-routeline-casing`;
if (this.map.getLayer(routeLineLayer)) {
if (lineStyle.color) {
this.map.setPaintProperty(routeLineLayer, 'line-color', lineStyle.color);
}
if (lineStyle.opacity !== undefined) {
this.map.setPaintProperty(routeLineLayer, 'line-opacity', lineStyle.opacity);
}
if (lineStyle.weight !== undefined) {
this.map.setPaintProperty(routeLineLayer, 'line-width', lineStyle.weight);
}
}
if (this.map.getLayer(routeLineCasingLayer)) {
if (lineStyle.color) {
this.map.setPaintProperty(routeLineCasingLayer, 'line-color', lineStyle.color);
}
if (lineStyle.opacity !== undefined) {
this.map.setPaintProperty(routeLineCasingLayer, 'line-opacity', lineStyle.opacity * 0.6);
}
}
}
private readdAllMarkers(): void {
// Re-add all markers to bring them to the front
for (const [id, marker] of Object.entries(this.markers)) {
this.markers[id] = this.recreateMarker(id, marker);
}
}
updateRoute(id: string, waypoints: LatLng[], options?: RouteOptions): void {
this.addRoute(id, waypoints, options);
}
removeRoute(id: string): void {
if (this.directions[id]) {
try {
this.directions[id].destroy();
} catch (e) {
console.warn('Error clearing directions:', e);
}
delete this.directions[id];
}
}
removeAllRoutes(): void {
Object.keys(this.directions).forEach(id => this.removeRoute(id));
}
on(type: string, event: (e: any) => void): void
{
this.map.on(type, event);
}
destroy(): void {
this.removeAllRoutes();
this.map.remove();
}
}

View File

@ -0,0 +1,97 @@
export interface MapOptions {
center: LatLng;
zoom: number;
styleUrl: string;
tileUrl: string;
}
export interface GeoPoint {
x: number;
y: number;
}
export interface Zone {
id: number;
name?: string;
color?: string;
opacity?: number;
polygon: GeoPoint[];
shippingFee?: number;
shippingScheduleStart?: string;
shippingScheduleEnd?: string;
}
export type LatLng = [number, number];
export function getLngLat(latLng: LatLng): [number, number] {
return [latLng[1], latLng[0]];
}
export function isPointInPolygon(polygon: LatLng[], point: LatLng): boolean {
let intersections = 0;
const x = point[0]; // lat
const y = point[1]; // lng
for (let i = 0; i < polygon.length; i++) {
const nextIndex = (i + 1) % polygon.length;
const x1 = polygon[i][0]; // lat
const y1 = polygon[i][1]; // lng
const x2 = polygon[nextIndex][0]; // lat
const y2 = polygon[nextIndex][1]; // lng
if ((y1 > y) !== (y2 > y)) {
const intersectionX = ((x2 - x1) * (y - y1)) / (y2 - y1) + x1;
if (x < intersectionX) {
intersections++;
}
}
}
return intersections % 2 === 1;
}
export interface RouteLineStyle {
color?: string;
opacity?: number;
weight?: number;
}
export interface RouteOptions {
serviceUrl?: string;
profile?: 'driving' | 'walking' | 'cycling';
lineStyle?: RouteLineStyle;
showMarkers?: boolean;
draggableWaypoints?: boolean;
}
export interface IMapAdapter<TMarker = any> {
init(container: HTMLElement, options: MapOptions): void;
setCenter(latLng: LatLng): void;
setZoom(zoom: number): void;
// Marker management
addMarker(latLng: LatLng, options?: {id?: string; color?: string; icon?: any}): void;
getMarker(id: string): TMarker | undefined;
getAllMarkers(): Record<string, TMarker>;
removeMarker(id?: string): void;
hasMarker(id: string): boolean;
updateMarkerIcon(id: string, icon: any): void;
updateMarkerPopup(id: string, content: HTMLElement): void;
addMarkerClickHandler(id: string, handler: (e: any) => void): void;
// Zone management
addZone(zone: Zone[]): void;
updateZone(zone: Zone[]): void;
openZonePopup(zone: Zone) : void
closePopup(): void;
// Route management
addRoute(id: string, waypoints: LatLng[], options?: RouteOptions): void;
updateRoute(id: string, waypoints: LatLng[], options?: RouteOptions): void;
removeRoute(id: string): void;
removeAllRoutes(): void;
// Utilities
destroy(): void;
on(
type: string,
event: (e: any) => void,
): void;
}

View File

@ -0,0 +1,105 @@
import {IMapAdapter, MapOptions, LatLng, getLngLat, Zone, RouteOptions} from './map-adapter.interface';
import { LibreAdapter } from './libre-adapter';
import { LeafletAdapter } from './leaflet-adapter';
export class MapFacade implements IMapAdapter<any> {
private readonly adapter: IMapAdapter<any>;
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: { id?: string; color?: string; icon?: any}): void {
this.adapter.addMarker(latLng, options);
}
getMarker(id: string): any | undefined {
return this.adapter.getMarker(id);
}
getAllMarkers(): Record<string, any> {
return this.adapter.getAllMarkers();
}
removeMarker(id?: string): void {
this.adapter.removeMarker(id);
}
hasMarker(id: string): boolean {
return this.adapter.hasMarker(id);
}
updateMarkerIcon(id: string, icon: any): void {
this.adapter.updateMarkerIcon(id, icon);
}
updateMarkerPopup(id: string, popup: any): void {
this.adapter.updateMarkerPopup(id, popup);
}
addMarkerClickHandler(id: string, handler: (e: any) => void): void {
this.adapter.addMarkerClickHandler(id, handler);
}
addZone(zones: Zone[]): void
{
this.adapter.addZone(zones);
}
updateZone(zones: Zone[]): void
{
this.adapter.updateZone(zones);
}
openZonePopup(zone: Zone) : void
{
this.adapter.openZonePopup(zone);
}
closePopup(): void
{
this.adapter.closePopup();
}
addRoute(id: string, waypoints: LatLng[], options?: RouteOptions): void {
this.adapter.addRoute(id, waypoints, options);
}
updateRoute(id: string, waypoints: LatLng[], options?: RouteOptions): void {
this.adapter.updateRoute(id, waypoints, options);
}
removeRoute(id: string): void {
this.adapter.removeRoute(id);
}
removeAllRoutes(): void {
this.adapter.removeAllRoutes();
}
on(type: string, event: (e: any) => void): void
{
this.adapter.on(type, event);
}
destroy(): void {
this.adapter.destroy();
}
}

View File

@ -0,0 +1,4 @@
.map-container {
width: 100%;
height: 100%;
}

View File

@ -0,0 +1,3 @@
<div #mapContainer class="map-container" webglDetection (webglSupport)="webglDetection($event)">
</div>

View File

@ -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);
}
}

View File

@ -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();
}
}
}

View File

@ -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';

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/lib",
"declaration": true,
"declarationMap": true,
"inlineSources": true,
"types": []
},
"exclude": [
"**/*.spec.ts"
]
}

View File

@ -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"
}
}

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": [
"**/*.spec.ts",
"**/*.d.ts"
]
}

33
tsconfig.json Normal file
View File

@ -0,0 +1,33 @@
/* 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. */
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"paths": {
"ngx-open-map-wrapper": [
"./dist/ngx-open-map-wrapper",
"./projects/ngx-open-map-wrapper/src/public-api.ts"
]
},
"skipLibCheck": true,
"isolatedModules": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"moduleResolution": "bundler",
"importHelpers": true,
"target": "ES2022",
"module": "ES2022"
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}

7191
yarn.lock Normal file

File diff suppressed because it is too large Load Diff