1

I have to load some scripts in my vue3 component, so this is what i'm doing:

<script setup>
import { onMounted } from 'vue'

function createEl (el, url, type) {
  const script = document.createElement(el)
  if (type) script.type = type
  script.src = url
  return script
}

onMounted(() => {
  const neshanScript = createEl('script', 'https://static.neshan.org/sdk/openlayers/5.3.0/ol.js', 'text/javascript')

  neshanScript.onload = () => {
    const map = new neshanScript.Map({
      target: 'map',
      maptype: 'neshan',
      poi: true,
      traffic: false
    })
    console.log(map)
  }

  neshanScript.onerror = () => console.log('error')
})

</script>


createEl function helps me to create any element I need, then I need to take an instance from my loaded script, but I onload block doesn't run!

2 Answers2

0

You are effectively calling 'onload' on your 'createEl' function by writing it this way and not on the Neshan SDK, which I assume is what you are trying to do.

I would suggest either instantiating the Neshan SDK in a separate js file and then importing it to this vue file, or putting the script tag in your index.html file. Also, note that 'ol' is exported by the SDK according to Nesham docs and you need an API key.

// Neshan.vue file

export default {
  setup() {
  
    const neshan = window.ol;     // 'ol' coming from index.html
    
    const map = new neshan.Map({
      target: 'map',
      key: 'YOUR_API_KEY'         // need API key from developer.neshan.org
      maptype: 'neshan',
      poi: true,
      traffic: false
    })

    console.log(map)
    
    return {
      neshan,
      map
    };
  },
};
<!-- index.html -->

   <link rel="stylesheet" type="text/css" href="https://static.neshan.org/sdk/openlayers/5.3.0/ol.css">
   <script type="text/javascript" src="https://static.neshan.org/sdk/openlayers/5.3.0/ol.js"></script>

Easiest method is probably to just use the Neshan Vue3 package (opensouce on GitHub).

npm i vue3-neshan-map-openlayers
Tim
  • 385
  • 6
0

so I figured it out! the loaded script must be added to the document so it could be used! one line added to createEl func:

function createEl (el, url, type) {
  const script = document.createElement(el)
  if (type) script.type = type
  script.src = url
  **document.body.appendChild(script)**
  return script
}