Forked from qannoufoualid/LeafletTilesFallbackDirective
Created
August 13, 2021 14:47
-
-
Save kaibeedevadmin/15a5d30da9c1d0bbc0d8ac48e7229cd7 to your computer and use it in GitHub Desktop.
Directive qui permet de gérer les fonds de cartes de leaflet en mode fallback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core'; | |
import * as L from 'leaflet'; | |
/** | |
* Directive qui permet de gérer les fallbacks de fonds de cartes de leaflet. | |
* Liste des serveurs de tiles open source: https://leaflet-extras.github.io/leaflet-providers/preview/ | |
*/ | |
@Directive({ | |
selector: '[leaflet-tiles-fallback]' | |
}) | |
export class LeafletTilesFallbackDirective implements OnChanges { | |
/** | |
* Suffixe d'image de la bretagne. | |
*/ | |
BRETAGNE_IMG = '6/31/22.png'; | |
/** | |
* Tableau contenant la liste des templates des urls de substitution | |
*/ | |
@Input('leafletFallbackTiles') templateURLFallbacks: string[]; | |
/** | |
* La reference vers l'objet tileLayer de la carte. | |
*/ | |
@Input('leafletTileLayer') tileLayer: L.tileLayer; | |
ngOnChanges(changes: SimpleChanges) { | |
if (changes.templateURLFallbacks && changes.templateURLFallbacks.currentValue) { | |
this.handleFallbacks(0); | |
} | |
} | |
/** | |
* Permet de vérifier les fallbacks une après une et utiliser celle qui marche (a.k.a le serveur qui répond par un status 200). | |
* @param index | |
*/ | |
async handleFallbacks(index: number) { | |
await this.checkStatus(this.getSampleImgURLFromTileTemplate(this.templateURLFallbacks[index])) | |
.then(() => { | |
this.tileLayer.setUrl(this.templateURLFallbacks[index]); | |
}) | |
.catch(() => { | |
if (index < this.templateURLFallbacks.length) { | |
this.handleFallbacks(index + 1); | |
} | |
}); | |
} | |
/** | |
* Permet d'extraire un échantillon d'image (Bretagne) en se basant sur le template url du serveur de tiles. | |
* @param templateURL | |
*/ | |
private getSampleImgURLFromTileTemplate(templateURL: string): string { | |
// Pour comprendre la structure d'une template url sur leaflet: https://leafletjs.com/reference-1.5.0.html#tilelayer | |
return templateURL.replace('{s}.', '') | |
.replace(/\{z\}.*/gi, this.BRETAGNE_IMG); | |
} | |
/** | |
* Permet de vérifier le status d'une image | |
* @param url | |
* @private | |
*/ | |
private checkStatus(url: string): Promise<unknown> { | |
return new Promise(function(resolve, reject){ | |
var img = new Image() | |
img.onload = function(){ | |
resolve(url) | |
} | |
img.onerror = function(){ | |
reject(url) | |
} | |
img.src = url | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment