Encountered SyntaxError: An unexpected token has been found while integrating leaflet with flask

Despite adding all necessary scripts and configuring my API_KEY in config.js, I keep getting an error message saying "Uncaught SyntaxError: Unexpected token." I have double-checked my API key multiple times, and it seems to be correct.

Here is a snippet from my Python file:

app.route("/")
def index():
    """Return the homepage."""
    return render_template("index.html", cities=cities, aqi=aqi, CO=CO, NO2=NO2, SO2=SO2, PM25=pm25)


if __name__ == "__main__":
    app.run()

The variables cities, aqi, etc., are lists that I am passing to index.html.

This is my index.html file:

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Air-Quality</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="../static/css/style.css">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.9.2/d3.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.js"></script>
    
    <!-- Other script tags -->

    <script>
        var cities = {{cities|tojson}};
        var aqi = {{aqi|tojson}};
        var CO = {{CO|tojson}};
        var NO2 = {{NO2|tojson}};
        var SO2 = {{SO2|tojson}};
        var PM25 = {{PM25|tojson}};
    </script>
</head>

<body>
    <div class="text-center main globe">
    </div>

In addition to this, there is JavaScript code that is invoking leaflet:

var myMap = L.map('globe', {
    center:[45.5017, -73.5673],
    zoom:1
});

L.tileLayer("https://{API_URL}/{z}/{x}/{y}.png?access_token={accessToken}", {
  maxZoom: 18,
  id: "mapbox.streets-basic",
  accessToken: API_KEY
}).addTo(myMap);

All the file paths are correct. I am puzzled about what could be going wrong. Thank you in advance.

Below is the full error message:

leaflet.css:3 Uncaught SyntaxError: Unexpected token .
leaflet.js:5 Uncaught Error: Map container not found.
    at i._initContainer (leaflet.js:5)
    at initialize (leaflet.js:5)
    at new i (leaflet.js:5)
    at Object.t.map (leaflet.js:5)
    at draw_globe.js:3

Answer №1

Be mindful of the errors you encounter. In this case, there is an issue with an unexpected token in leaflet.css, specifically on line 3. The problem stems from attempting to load a CSS file as if it were JavaScript. This approach will not yield the desired outcome. To resolve this, you must specify the stylesheet using a <link> tag. Instead of:

<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.css"></script>

You should use:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.css">

It's important to note that the URL ending with .css necessitates this treatment, unlike files ending in

.js</code which are typically included using <code><script>
tags like so:

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.9.2/d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.js"></script>

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

Numerous websites with scroll-based navigation

I am currently building a unique website that includes scrolling in various directions without the use of a horizontal scrollbar. The design is similar to this image: https://i.stack.imgur.com/Ex2Bf.jpg. It is a one-page website where vertical scrolling ...

Secure login using AngularJS

I am in need of modifying the code on this Plunker: plnkr.co/edit/Mvrte4?p=preview I want to remove user roles so that all users have access to the same page. If possible, I would like the modified code to be split into two pages: Page 1: index.html co ...

A method in JQuery to replace an input with a select element is by using the replace

I have multiple input fields with pre-existing values. My goal is to replace these inputs with select dropdowns that have the same options while retaining the original values. Here is the current HTML structure: <span id="span1"> <input type=" ...

The $scope object in Angular is supposed to display the $scope.data, but for some reason, when I attempt to access it

Having an issue with my controller that fetches data from a service. After receiving the data in the controller, I'm using $scope to pass it to the view. Strange behavior - console.logs inside the 'then' function display the data correctly ...

Select elements from a PHP loop

As part of my school project, I am developing a basic webshop. Currently, I am using a while loop to display featured products on the homepage. However, I now need to implement a shopping cart functionality. After a user clicks the "add to cart" button, th ...

Preventing the removal of a choice by disabling it in the selector

I have a unique selector that is designed like this: <select id="patientSelector"> <option disabled selected style='display: none;' id="select0"> New Patients to Come</option> <option id="select1"></opt ...

In Internet Explorer 7, a newline within a <pre> tag may cause display issues

Within my ASP.NET MVC 3 project, I am working with the following code: <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" ty ...

Limiting character count in jQuery using JSON

I am trying to manipulate the output of a snippet of code in my jQuery: <li> Speed MPH: ' + val.speed_mph + '</li>\ that is being pulled from a JSON endpoint and currently displays as: Speed MPH: 7.671862999999999 Is there a ...

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...

Creating a Typescript interface for a anonymous function being passed into a React component

I have been exploring the use of Typescript in conjunction with React functional components, particularly when utilizing a Bootstrap modal component. I encountered some confusion regarding how to properly define the Typescript interface for the component w ...

A step-by-step guide on utilizing jQuery to cyclically change the background color of elements upon clicking, and resetting the colors upon clicking another element

So I've been working on a solution to change the background color for accessibility purposes on a client's website. To achieve this, I have a set of div elements with different background colors and I'm using jQuery to update the body backgr ...

Encountering difficulties with showing contact images in phonegap using angularjs

In my project, I encountered an issue where I can fetch and display the contact photo using simple HTML and JavaScript. However, when I attempt to do the same using AngularJS model, I encounter an error. Below is the code snippet that I am struggling with: ...

As I embark on building my web application using next.js, I begin by importing firebase from the "firebase" package. Unfortunately, a particular error unexpectedly surfaces in the terminal

I am currently developing a next.js web application and I have decided to utilize firebase for both database management and authentication. However, when attempting to import firebase in a specific file, I encountered the following error: Error - ./firebas ...

Is your blockui overlay failing to cover the entire page?

I have implemented blockui to display a "Wait ... loading" popup on my webpage. It is mostly working fine, but I am facing a small issue where the overlay does not cover the entire width of the scroll window when I scroll right (although it covers the full ...

javascript verify that the input is a valid JSON object

Seeking assistance with an if statement that checks for a json object: updateStudentData = function(addUpdateData) { var rowDataToSave; if(addUpdateData.data.row) { rowDataToSave = addUpdateData.data.row; } else { rowDataToSav ...

How to toggle between displaying divs using JavaScript and Jquery

How can I use JavaScript to show or hide specific divs on page load and upon clicking different links? I want to display the "houseImages" div by default, while hiding the "landImages", "renovationImages", "UpcomingImages", and "voteForNext" divs. Then, w ...

Navigating Express HTTP Requests within Apollo Link Context in a NextJS Web Application

Currently, I am in the process of developing a NextJS application and facing a challenge with accessing a cookie to utilize it for setting a Http Header within a GraphQL Request. For this task, I am integrating apollo-link-context. Below is the snippet of ...

Checking the length of user input with JavaScript

To ensure that the user enters at least 4 letters in a text box and show an error if they don't, I need help with the following code. It is partially working but currently allows submission even after showing the error message. I want to prevent subm ...

Tips for aligning a div (or any other content) in the center of a

I recently added a small div to my webpage to display 3 options in a stylish way, but I'm encountering an issue - the box is appearing on the left side instead of the center. I have tried using various CSS properties like align-items, align-content, a ...

Exploring the Possibilities: Incorporating xlsx Files in Angular 5

Is there a way to read just the first three records from an xlsx file without causing the browser to crash? I need assistance with finding a solution that allows me to achieve this without storing all the data in memory during the parsing process. P.S: I ...