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

I am curious as to why the Bootstrap 4 dropright selected menu appears as a default browser button in Chrome, while it functions seamlessly in Firefox

An issue has been identified that is specific to Chrome. The dropright selected menu appears differently in Chrome compared to Firefox, where it displays correctly with a white background. !https://i.sstatic.net/BulRA.jpg The Bootstrap version being used ...

What is the best way to center a div within another div without using the margin tag?

I am struggling to find a way to center a container (div) on my webpage. I've tried various methods like using margin:auto, margin:0 auto;, margin-left:auto;, and margin-right:auto;, but none of them seem to work. Additionally, I'm unsure about ...

Add a variety of icons to every item in a list using HTML

Is there a way to display multiple icons on the left side of each element, with the option to have none or many? If so, could you please guide me in the right direction. <header> <nav> <ul> <a href="http://localhost:4000 ...

Can Cesium "separate" intersecting polylines?

Currently, I am utilizing Cesium and aiming to visually display multiple polylines between two entities. Specifically, I want a green polyline from entity A to entity B, as well as a blue polyline from entity A to entity B. My intention is for these lines ...

Utilizing a Web Interface for Remote Monitoring of Windows Servers

I am in need of creating a webpage that will indicate whether a server is currently operational or not. These servers are all Windows based, with some running on 2008 and others on 2003. They are spread across different networks within various client locat ...

Having trouble accessing a CSV file with JQuery and FileContentResult?

How can I make an ajax call without using ActionLink in my controller? Here is a snippet of my controller code: public IActionResult ExportUsers(List<string> listOfEmails) { /*some data processing*/ return File(result, "text/csv", ...

Connect the input field to the grid component

How can I sync the value of the SearchFilter with the FilterGrid to effectively filter the data (refer to code below)? I'm facing an issue where the field clears out the value as I type. There seems to be a problem in how I'm utilizing the state ...

Accessing BIM Components: Identifying Global and Express IDs through Selection

As I delve into the task of handpicking specific elements from the intricate web of an IFC model, my approach involves utilizing a SimpleRayCaster to cast a ray onto the object with relative success. The challenge lies in identifying the exact entity inter ...

Establish a JavaScript hyperlink to assign a value to a shared rendering parameter

In my attempt to create a JavaScript link that, when clicked, assigns a value to a public render parameter in WebSphere Portal, I'm encountering unexpected code instead of the intended value. Here is how I am constructing the link using JavaScript: ...

How does the question mark symbol (?) behave when utilizing it in response? Specifically in relation to data, the API, and the fetch API

Have you encountered the curious sequence of symbols in this context? data?.name Could you explain the significance of the question mark (?) between 'data' and the period? ...

Can you explain the functionality of the following Express router?

In the tutorial I am currently following, there are 2 router methods used to retrieve articles from the database. router.param('article', function(req, res, next, slug) { Article.findOne({ slug: slug}) .populate('author') .th ...

Issue with React event hierarchy

How can I effectively manage state changes in a deep node that also need to be handled by a parent node? Let me explain my scenario: <Table> <Row prop={user1}> <Column prop={user1_col1} /> <Column prop={user1_col2} /> ...

Eliminating the Skewed Appearance of Text in Input Fields Using CSS

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Customized Page Layout</title> <script src="https://c ...

Implement the use of NextAuth to save the session during registration by utilizing the email and password

When registering a user using email, password and username and storing in mongodb, I am looking to incorporate Next Auth to store sessions at the time of registration. My goal is to redirect the user in the same way during registration as they would experi ...

selection menu and advancement gauge

While working on my code, I have a task where I need to make the progress bar move a specific amount when a name is clicked based on the option's value. <!DOCTYPE html> <html> <head> <title>testinggg</title> &l ...

Angular and WEB API experiencing issues with the update function synchronization

Currently, I'm developing a CRUD example using dotnet core and Angular. In the backend, I have implemented a function in the CarController.cs as shown below: CarController.cs [Route("UpdateCar")] [HttpPut] public IActionResult Put([ ...

How to Use $scope within a Function in AngularJS

When a page is loaded, I run the following function: $scope.showTags = function(Id) { $scope.toggleSelectedBlocks = function selectB(block) { // There is a checkbox to be selected... } $scope.greetUser() { console.log("GREETIN ...

Attempting to dynamically update the title of a Vue Meta page using a combination of a string and

In the blog application for my project using Nuxt JS 2.4.5, I am utilizing Vue Meta. I'm encountering difficulties while attempting to set the title along with a variable from data (), and it seems like something crucial is eluding me. Despite tryin ...

Unable to get Bootstrap IMG-RESPONSIVE to function properly in Firefox and IE within the navbar

I recently encountered an issue with the Bootstrap IMG-RESPONSIVE class not functioning properly in the navigation bar on Firefox and IE. Oddly enough, it was working perfectly just a few days ago until I made some unknown changes, causing it to only work ...

Unable to get PrependTo to remove itself when clicked

Below is a custom jQuery script I put together: $(function(){ $("a img").click(function() { $("<div id=\"overlay\"></div>").hide().prependTo("body").fadeIn(100); $("body").css({ ...