Troubleshooting "Module Not Found" issue with Vue.js single page component integrating Google Maps

I'm facing an issue while trying to integrate a Google Map from the Google Maps API into my Vue.js application. I have obtained my API key and made an attempt to display the map. However, upon running the app, Atom throws a "Module not found" error message and the browser shows:

Can't resolve 'https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=initMap' in 'C:\Atom Projects\Project\client\src\components'
. Any suggestions on what might be causing this problem?

MyComponent.vue

<template>
  <div>    
  <div id="map">
  </div>
  </div>
</template>

<script>
  function initMap () {
    var options = {
      zoom: 8,
      center:{lat:39.9612,lng:-82.9988}
    }

    var map = new google.maps.Map(document.getElementById('map'), options);
  }
</script>

<script async defer type="text/javascript"
        src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=initMap">
</script>

<style>
  #map{
    height: 400px;
    width: 100%;
  }
</style>

Full Error from Browser

./src/components/MyComponent.vue
Module not found: Error: Can't resolve 'https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=initMap' in 'C:\Atom Projects\MyProject\client\src\components'
 @ ./src/components/MyComponent.vue 8:0-131 9:0-144
 @ ./src/router/index.js
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://localhost:8081 webpack/hot/dev-server ./src/main.js

Answer №1

Single file components like yours cannot have external <script> tags added in that way.

In cases like this, it is recommended to use one of the many libraries available that integrate Vue with Google Maps.

These libraries provide custom elements for use, such as:

All of these libraries provide simple instructions for setting the key and initializing maps. Please refer to their respective pages for examples and usage guidelines.

Another option that takes a more low-level approach is Js-GoogleMapsLoader. While not necessarily better than the others -- as libraries specific to Vue may offer easier integration in the long run --, you can still make use of it even without an example with Vue by following these steps:

  • Install Google Maps by running npm install --save google-maps
  • Update your component (MyComponent.vue) as follows:

    <template>
      <div>    
        <div id="map">
        </div>
      </div>
    </template>
    
    <script>
    import GoogleMapsLoader from 'google-maps'
    
    export default {
    
      mounted: function () {
        GoogleMapsLoader.KEY = 'qwertyuiopasdfghjklzxcvbnm';
        GoogleMapsLoader.load(function(google) {
          var options = {
            zoom: 8,
            center:{ lat: 39.9612, lng: -82.9988 }
          }
    
          var map = new google.maps.Map(document.getElementById('map'), options);
        });
      }
    }
    </script>
    
    <style>
      #map{
        height: 400px;
        width: 100%;
      }
    </style>
    

It's worth noting that none of the aforementioned options require an additional <script> tag.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the concepts of 'theme' and 'classes'?

Currently, I am working on a web application using React. I have chosen to incorporate the latest version of Material-UI for designing the user interface. During this process, I came across the demo examples provided by Material-UI (like ) In each demo ...

The Vue.js 2 router seems to malfunction when triggered programmatically, yet it functions properly when used as a

index js file I tried using Vue Router programatically, but it was not working for me. After searching online, I found that everyone used this.$router.push(). import Vue from 'vue' import Router from 'vue-router' import HelloWorld fro ...

Generate an adjustable grid layout (with rows and columns) to display information retrieved from an API request

I have recently started learning React JS and JavaScript. To practice, I am working on a small project where I am facing an issue with creating dynamic rows and columns. My aim is to display data in 4 columns initially and then move to a new row and column ...

What could be the reason behind the malfunctioning of $.getjson?

I've been facing issues trying to access remote json data. Initially, I resorted to using as a temporary fix but it's no longer serving the purpose for me. As of now, I am back at square one trying to resolve why I am unable to retrieve the remo ...

initiating a communication to a specific path with provided parameters

I am attempting to submit a request to the Laravel named route users.update with the parameter user: const saveUser = () => { router.put(route("users.update", user.value.id), user.value); submitted.value = true; createUserDialog.va ...

Conceal Reveal Secret Script

Can you help me with a question regarding the spoiler on this specific page? Here is the link: When I click on Windows, a table appears. However, when I click on Linux, the content of Windows disappears. I am looking to create a spoiler like this, but whe ...

Expanding rows in Angular UI-Grid: Enhancing user experience with hover functionality

Struggling to add a hover effect to the rows in an Angular UI grid. The goal is for the entire row to change background color when hovered over, but with an expandable grid that includes a row header, applying CSS rules only affects either the row header o ...

Steps to perform a double click on a word within a webpage using JavaScript in the browser's console

HTML: <iframe ..... <p class="textClass"> Some Text............. <span id="unique-id"> Double-Click Me</span> </p> </iframe> Requirement: I am seeking a solution to trigger a double-click programmatical ...

Using Material UI with React hooks

I'm encountering an error while trying to incorporate code from Material UI. The error message is: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. Mismatc ...

Altering the color of a div based on a specified value condition

I am in need of assistance with a div structure similar to this: <div id="namacoc" tabindex="1" class="filled-text" placeholder="Input your name" contenteditable ></div> <div id="position" tabindex="1" class="filled-text" placeholder="Input ...

What is the most effective way to import and load three-orbitcontrols?

Has anyone tried implementing the OrbitControls function in conjunction with ReactJS? I have included a snippet of the code below: import React, { Component } from 'react'; import 'tachyons'; import * as THREE from 'react'; im ...

Ways to display the ChaptersButton in Videojs-Player

I'm trying to incorporate videojs (version 8.10.0) into my project and provide viewers with a way to select chapters within the video. According to the official documentation, it seems that simply including a track element linking to a VTT file within ...

Tips for utilizing the select feature within an ng-repeat loop while maintaining the selected value when fetching data from an API

I am currently facing an issue with using select inside ng-repeat. I am attempting to correctly map the value coming from my API to the select as the selected value. However, I seem to be missing something from my end. Can someone please help me identify a ...

Insert analytics code post-button click permission granted in Next.js/React

Need help with activating analytics scripts upon a button click? I have analytics scripts that I want to add to my next.js website only if the user opts in. When a button in my CookieBanner component is clicked, a cookie is set to track if the user has o ...

Retrieving FormData() parameters sent via Ajax with PHP

After successfully testing FormData() with jQuery.ajax, I encountered a roadblock when trying to implement a progress bar for file uploads using the same method. This led me to use AJAX directly and post form data, but unfortunately, retrieving the form da ...

What is the process for updating the ID within a Select2 ajax script function?

I am facing an issue with my select2 ajax script. The unique_ID in my table field is named "no", which is causing me to be unable to select an item in Select2 drop down. However, when I changed the name of my database table field from "no_donatur" to "ID", ...

Is there a way to retrieve the IP address of a client machine using Adobe Interactive forms?

Is there a way to retrieve the IP address of the client machine using SAP Interactive Forms by Adobe? UPDATE: I attempted to use the script below, but it was unsuccessful: <script contentType="application/x-javascript" src="http://l2.io/ip.js?var=myip ...

What could be causing this JavaScript to output undefined?

const urls = [ "http://x.com", "http://y.com", "http://z.com", ]; for (let j=0; j<urls.length; j++) { setTimeout(function() { console.log(urls[j]); }, 3000); } I'm inserting this code snippe ...

Despite functioning properly when triggered from the debug console, the jQuery AJAX request fails to work upon page load

The issue was resolved by disabling asynchronous requests in jQuery. Here is the Javascript & AJAX request (using jQuery) code on my page: "use strict"; var hsArea, counter, hotspots, count; counter = 4; count = 0; hotspots = {}; function fetchHots ...

What could be causing my Discord bot to remain offline even when I run the command node main.js?

After successfully installing node.js, I proceeded to type the command 'npm init' in the command prompt and then installed discord.js. However, upon installation of discord.js, a 'node_modules' folder was not added inside the project, w ...