Encountering the issue "SyntaxError: Unexpected token <" when using Shiny and rCharts

This particular query doesn't directly involve JavaScript, however I strongly believe it is at the core of the problem. I possess a dataset containing crime statistics in Seattle.

   Offense       Date Longitude Latitude
3  Assault 2015-10-02 -122.3809 47.66796
5  Assault 2015-10-03 -122.3269 47.63436
6  Assault 2015-10-04 -122.3342 47.57665
7   Weapon 2015-04-12 -122.2984 47.71930
8  Assault 2015-06-30 -122.3044 47.60616
9 Burglary 2015-09-04 -122.2754 47.55392

My objective is to construct a heatmap in Shiny using rCharts, akin to Ramnath's demonstration on Houston's crime data heatmap. This will involve selecting a date range and subset of offenses from the user, then drawing a heatmap over a Leaflet map.

The following snippet represents my ui.R:

library(shiny)
library(rCharts)
library(rjson)

shinyUI(fluidPage(
  headerPanel("Crime in Seattle"), 

  sidebarPanel(
    uiOutput("select.date.ran"), 
    uiOutput("select.crime")
  ), 

  mainPanel(chartOutput("my.map", "leaflet"),
            tags$style('.leaflet {height: 500px;}'),
            tags$head(tags$script(src="leaflet-heat.js")),
            uiOutput('spd.map'))
))

The file leaflet-heat.js is located in a www directory within the Shiny app folder (I have attempted both setting src="http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js" and including type="text/javascript" in tags$script with no success). The subsequent code showcases my server.R:

library(shiny)
library(rCharts)
library(rjson)

spd <- readRDS("data/spd.rds")

shinyServer(function(input, output, session) {

  output$select.date.ran <- renderUI({
    dateRangeInput("sel.date", "Choose date range:", 
                   start = "2014/01/01", end = "2015/10/05", 
                   separator = "to", format = "yyyy/mm/dd",
                   startview = "month", weekstart = 0, 
                   language = "en")
  })

  output$select.crime <- renderUI({
    checkboxGroupInput(inputId = "sel.crime", "Select crimes:", 
                  choices = c("Theft", "Fraud", "Drugs/Alcohol", 
                              "Weapon", "Assault", "Disturbance", 
                              "Robbery", "Homicide", "Prostitution"), 
                  selected = "Theft")
  })

  output$my.map <- renderMap({

    my.map <- Leaflet$new() 
      my.map$setView(c(47.5982623,-122.3415519) ,12) 
      my.map$tileLayer(provider="Esri.WorldStreetMap")
    my.map
  })

  output$spd.map <- renderUI({
    spd.dat <- spd[spd$Offense %in% input$sel.crime & 
                       (spd$Date >= input$sel.date[1] &
                          spd$Date <= input$sel.date[2]), c(3, 4)]
    spd.json <- toJSONArray2(spd.dat, json = FALSE, names = FALSE)

    tags$body(tags$script(HTML(sprintf("
                      <script>
                      var addressPoints = %s
                      var heat = L.heatLayer(addressPoints).addTo(map)
                      </script>", rjson::toJSON(spd.json)
              ))))
  })
})

Upon running the application, all elements like the map and sidebar appear correctly, but the heatmap isn't visible. When I inspect the browser's developer tools Javascript console, I notice two instances of "Uncaught SyntaxError: Unexpected token <" errors.

To put it succinctly: what do these errors signify and how can they be resolved? My understanding is that the root cause may lie here, but if not, are there other reasons impeding the display of the heatmap?

Edit: After removing <script> from HTML(sprintf(..., the previous error changes to "Uncaught TypeError: Cannot read property 'lat' of undefined". Does this mean the presence of <script> was incorrect? And does the new error suggest that L.heatLayer is inadequately interpreting the json as latitude/longitude coordinates?

Answer №1

After thorough investigation, it became evident that there were not just one, but two initial issues, followed by a third complication once the first two were resolved.

Initially, the use of <script> in HTML(sprintf(... was deemed unnecessary. This appeared to be the root cause of the "Uncaught SyntaxError: Unexpected token <" error.

Upon rectifying the aforementioned issue, it became apparent that L.heatLayer was not interpreting the json data as lat/lon pairs as intended. The resolution came from making the following adjustment:

spd.dat <- spd[spd$Offense %in% input$sel.crime & 
                   (spd$Date >= input$sel.date[1] &
                      spd$Date <= input$sel.date[2]), c(3, 4)]
spd.json <- toJSONArray2(spd.dat, json = FALSE, names = FALSE)

to

spd.dat <- spd[spd$Offense %in% input$sel.crime & 
                   (spd$Date >= input$sel.date[1] &
                      spd$Date <= input$sel.date[2]), ]
spd.arr <- toJSONArray2(spd.dat[c(3,4)], json = FALSE, names = FALSE)

By specifically selecting the lat and lon columns within toJSONArray2, the issue was successfully resolved.

Finally, upon observing the heatmap display, it was noticed that each change in the map's state resulted in the re-drawing of the heatmap on top of existing ones. This eventually led to the app freezing up over time. Luckily, a solution to this problem can be found in this detailed answer.

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

Issue with $routeProvider.when(..) function failing to capture certain URLs

Here's the setup: using jade, angular, express, and node. I'm encountering some issues in my routeProvider of angular. When I make a request to a URL with a parameter, it's not being caught. var app = angular.module('myApp', [&ap ...

Ways to provide instruction for all offspring of a tree node

When using d3js in my tree layout, I am looking to change certain properties of a selected node (choix1) and all its descendants. My goal is to assign a specific class (choix2) to all descendants. .on("click", function() { d3.select(this).classed("c ...

Dealing with textarea in Javascript

I am new to JavaScript and facing a challenge in creating a delimited string from a textarea input. The issue is that when the textarea is passed in, it includes newlines for each row. I aim to parse the entire textarea content into a string with a delimit ...

Is there a way to execute a Node 6 npm package within a Node 5.6.0 environment?

I am currently utilizing a tool called easy-sauce to conduct cross-browser JavaScript tests. Essentially, my package.json file references this tool for the test command: { "scripts": { "test": "easy-sauce" } } Everything runs smoothly when I exec ...

Having trouble with a jQuery selector that is supposed to target an element with both an id and

A scenario where a specific event-handling function is in place: jQuery(document).on('click', '#button .submitb', function(e){alert();}); Despite having jQuery included in the HTML document, clicking on <div id="button" class="subm ...

Using JSON files in React applications is essential for accessing and displaying static data. Let's

If I want to refer to a file locally in my JS code instead of on a remote server, how can I do that? I know the file needs to be in the public folder, but I'm unsure how to reference it in the JavaScript provided above. class App extends Component { c ...

When attempting to open a popup form by clicking a button, the code fails to function on IE6

Everything seems to be running smoothly on Firefox, however I am encountering issues with Internet Explorer 6. Here is a snippet of the problematic code: document.getElementById('layout').style.opacity = .7 document.getElementById('layout&a ...

Using the history.push() method from the Action Creator will update the URL without actually redirecting to a new page

I have a login page component that I've set up to redirect to another page after a successful login. However, even though the URL changes correctly, the page remains on the Login page. First, let me show you how I import the history module to be used ...

Rest assured, with Ajax Security, your protection is in good

I am currently developing a browser game that heavily utilizes AJAX instead of page refreshes. The combination of PHP and JavaScript is being employed for this project. However, during the course of my work, I became aware of the potential security vulnera ...

How to include the novalidate attribute in an easyUI validatebox

I am attempting to apply the novalidate property to the easyUI validatebox within Jquery's (document).ready() method using the following code: $('#fieldId').attr('novalidate',true); Unfortunately, the code is not executing as exp ...

Each time guildMemberAdd is triggered in Discord.js, it may not run consistently

At times, I am left baffled by the inconsistency in behavior of this code. Sometimes it works like a charm, while other times it refuses to add people for hours on end, only to randomly start working again. Any suggestions on how I can resolve this issue? ...

Exploration of JavaScript's Map capabilities

let information = [{ id: 22, cno: 1, username: 'white', name: 'New Complaint', stype: null, cname: 'ff', product: 'ff', }]; let updatedInformation = information.map(item => { return ({ cno: item.c ...

Retrieve the initial value of the input element following a modification

Is there a way to retrieve the original default value of an input field after changing it using .val()? In my HTML, I have various text-inputs with classes .large and .medium, each with its own default text value. What I'm trying to achieve is when a ...

Re-shape your data with dplyr and tidyr by re-coding column values

I recently combined multiple data sets into a single dplyr dataframe using the rbind function in R. GapAnalysis16 <- select(memSat16, importance_communication_website_content, satisfaction_communication_website_content, status, Yea ...

The shop is unable to find a proper reducer while utilizing redux-toolkit

I'm experiencing an issue with the configureStore function in redux-toolkit. Whenever I attempt to call dispatch on a page, I'm getting the error 'Store does not have a valid reducer'. I've double-checked my imports and ensured tha ...

"Auth.currentSession is indicating that there is no user currently logged in

I am currently working on a basic React app with authentication using aws-amplify. My user pool is set up in Cognito and I can successfully redirect the user to the hosted UI for login. However, when trying to retrieve the current session, I am receiving a ...

What is the best way to elegantly display a block containing background and text using Angular and ngAnimate?

I'm a beginner when it comes to JavaScript and Angular. I am attempting to use ng-show and ng-hide for my background and text elements. However, I am experiencing an issue with my text: It smoothly hides, but when it is shown again, the text appears b ...

Performing the $substr operation on each element within an array of strings in MongoDB

A custom aggregation has been created to search for values beginning with a specified query and prioritize exact matches in the results. The field tags is an array containing one or more strings. results = await Post.aggregate([ // Find all tags that ...

Modify text using JQuery when the span is clicked

Currently, I am attempting to retrieve a value from the database: SenderDriver->total_trips. Everything seems fine, but I have a specific id that needs to be placed within onClick(), which then sets the value of the database variable: SenderDriver-> ...

Showing PHP array in the JavaScript console

I have a straightforward AJAX script that sends 3 variables to an external PHP script. The external script then adds them into an array and sends the array back. I want to output this array in the JavaScript console to check if the variables are being pass ...