How to use the bing maps api inside a vue js application to display a map ?
Note: I use Bing maps V8 and vuejs 2.5.17.
This is my template
<template>
<div id="map"></div>
</template>
This is my style
<style lang="scss" scoped>
#map {
height: 300px;
width: 500px;
}
</style>
This is my script part (I use class based object component)
mounted() {
let mapElement: HTMLElement = <HTMLElement>document.getElementById("map")
var map = new Microsoft.Maps.Map(mapElement, {
credentials: [API_KEY]
});
}
This is how I include the external script from the cdn inside my app. After some research, I have found and tried 2 options below
Option 1: I have included the script directly in my index.html file:
<!-- index.html -->
...
<head>
...
<script src="https://www.bing.com/api/maps/mapcontrol?key=[API_KEY]" async defer></script>
</head>
Option 2: I inject programmaticaly the script in the document from my component in the mounted method as below
mounted() {
// Add programmaticaly the external Bing maps api script
var scriptTag = document.createElement("script");
scriptTag.src = "https://www.bing.com/api/maps/mapcontrol";
scriptTag.id = "bingApiMaps";
// Inject the dynamic script in the DOM
document.head.appendChild(scriptTag);
...
}
In both, I have the follow error and I dont understand why:
[Vue warn]: Error in mounted hook: "ReferenceError: Microsoft is not defined"
I've transcripted rdhainaut's answer to JavaScript:
mounted: function() {
if (document.getElementById("scriptBingMaps")) {
return; // already loaded
}
// Add a global function for the callback from Bing Maps api
window.OnLoadBingMapsApi = () => this.InitMap();
// Add programmaticaly the external Bing maps api script
var scriptTag = document.createElement("script");
scriptTag.src = "https://www.bing.com/api/maps/mapcontrol?callback=OnLoadBingMapsApi&key=[BING_API_KEY]";
scriptTag.id = "scriptBingMaps";
// Inject the dynamic script in the DOM
document.head.appendChild(scriptTag);
},
methods: {
InitMap: function() {
var mapElement = this.$refs.myMap;
this.map = new Microsoft.Maps.Map(mapElement, {
mapTypeId: Microsoft.Maps.MapTypeId.aerial,
zoom: 15,
maxZoom: 21,
//minZoom: 15,
center: new Microsoft.Maps.Location(52.7759872, -1.5119702),
maxNetworkLinkDepth: 3
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With