问题
While initializing the here-map api in order to render the map in a vue component I am getting the following error:
"'H' is not defined
src/components/HelloWorld.vue:15:26
const platform = new H.service.Platform({...})"
I have included the headers for here-maps in index.html as required at and my component code is:
<template>
<div>
<div style="width: 100%; height: 500px" id="map-container"></div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data: () => ({ map: null }),
mounted () {
// Initialize the platform object:
const platform = new H.service.Platform({
app_id: 'nEpmlsRnNdUOVqzCSjdM',
app_code: 'pDktey4pqzO2OlZusMCQPA',
useCIT: true,
useHTTPS: true
})
const maptypes = platform.createDefaultLayers()
// Instantiate (and display) a map object:
this.map = new H.Map(
this.$el.getElementById('map-container'),
maptypes.normal.map,
{
zoom: 10,
center: { lng: 13.4, lat: 52.51 }
}
)
}
}
</script>
Edit: here is my index.html code for including api calls
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.0/mapsjs-ui.css?dp-version=1533195059" />
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-core.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-service.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-ui.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-mapevents.js"></script>
</head>
I am trying to display the map on my user interface using the provided api. What am I missing?
回答1:
The Vue component does not have access to the global scope, that’s why it gives an error – the build system assumes that the variable was never defined. There are several ways to achieve the desired result and it depends on the application architechture.
One can use instance properties to provide access to the global variable from within a Vue component (https://vuejs.org/v2/cookbook/adding-instance-properties.html#Base-Example)
The code, most likely will look like that: Vue.prototype.$H = self.H // Added to the main.js
And the component calls tot he „H“ namesapce must be changed to „this.$H“
Alternatively one can use Vue.mixins, write a plugin or even access the global variable through the direct call to self.H (not recommended) Saying that, the particular way where and how provide the namespace or instantiate the map must be decided by the application developer. Hope this helps.
来源:https://stackoverflow.com/questions/51843642/map-application-using-vue-nodejs