I’m trying to dynamically show a map on the product page wit latitude and longitude coordinates or just city name. I cant get the map to show
This is what I have so far, this is the html:
<div>
<iframe
allowfullscreen
height="450"
loading="lazy"
referrerpolicy="no-referrer-when-downgrade"
[src]="getMapUrl()"
style="border:0"
width="600"
></iframe>
</div>
this is the typescript:
ngOnInit(): void {
this.route.paramMap.subscribe((params: ParamMap) => {
this.productId = Number(params.get('productId'));
this.boatName = params.get('name') as string;
console.log(this.productId + ": productId")
console.log(this.boatName + ": boatName")
// console.log("Coords: " + this.boat.latitude + ", " + this.boat.latitude);
document.title = `${this.boatName} || Boat and Share`;
// call the product service to fetch the product details
this.boatsService.getProductById(this.productId).subscribe(boat => {
this.boat = boat;
console.log("The boat: " + this.boat.name + ', ' + this.boat.boatType)
his.getMapUrl()
});
});
}
getMapUrl(): string {
const latitude = this.boat.latitude;
const longitude = this.boat.longitude;
return `https://www.google.com/maps/embed/v1/place?key=${environment.apiMapsKey}&q=${this.boat.latitude},${this.boat.longitude}`;
}
All help is highly appreciated!
EDIT:
The errors I get in the console in the browser
ERROR Error: NG0904: unsafe value used in a resource URL context (see https://g.co/ng/security#xss)
at ɵɵsanitizeResourceUrl (core.mjs:7391:11)
at elementPropertyInternal (core.mjs:10839:37)
at Module.ɵɵproperty (core.mjs:13584:9)
at ProductInfoComponent_div_0_Template (product-info.component.html:153:15)
at executeTemplate (core.mjs:10481:9)
at refreshView (core.mjs:10366:13)
at refreshEmbeddedViews (core.mjs:11381:17)
at refreshView (core.mjs:10390:9)
at refreshComponent (core.mjs:11427:13)
at refreshChildComponents (core.mjs:10157:9)
The error you are getting is because Angular deems the use of the returned data from getMapUrl
to be vulnerable to a XSS attack.
Try wrapping your return value in getMapUrl
in sanitizer.bypassSecurityTrustUrl()
getMapUrl(): string {
const latitude = this.boat.latitude;
const longitude = this.boat.longitude;
return sanitizer.bypassSecurityTrustUrl(`https://www.google.com/maps/embed/v1/place?key=${environment.apiMapsKey}&q=${this.boat.latitude},${this.boat.longitude}`);
}
This tells Angular that you want to bypass security and use the unsafe value.