Building Multiple Marker Layers with Leaflet

I am attempting to create a map of New York City with markers using Leaflet. Right now, I am following a tutorial for guidance:

http://bl.ocks.org/ragnarheidar/a711faa1a94be4dae48f

This is the code I am currently working with:

<!-- http://data.nycprepared.org/dataset/nyc-community-districts/resource/f990d0e5-2917-4902-a50a-1f6a74cc612b -->

<!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <title>NY Noise Map</title>
            <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> 
            <script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
            <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
            <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
        </head>
        <body>
            <div id="map"></div>
        </body>
        <script type="text/javascript">
            var width = 1280,
                height = 960,
                active = d3.select(null);

            /* Map definition */
            // Set map wrapper size
            d3.select('#map')
              .style('width', width + 'px')
              .style('height', height + 'px');

            // Create Leftlet map and center in the desired position
            var map = L.map('map').setView([40.658528, -73.952551], 10);

            // Load a tile layer  
            L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { 
                attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a>',
                maxZoom: 18, 
                minZoom: 10
            }).addTo(map);

            // Interaction
            var geojson;
            function style(feature) {
                return {
                    fillColor: '#FFEDA0',
                    weight: 1,
                    opacity: 1,
                    color: 'white',
                    dashArray: '3',
                    fillOpacity: 0.7
                };
            }

            function highlightFeature(e) {
                var layer = e.target;

                layer.setStyle({
                    weight: 3,
                    color: '#666',
                    dashArray: '',
                    fillOpacity: 0.7
                });

                if (!L.Browser.ie && !L.Browser.opera) {
                    layer.bringToFront();
                }
            }

            // Other functions skipped for brevity...
            
            // Info control

            // Error message image link omitted...

            <p>I'm unsure what might be causing this issue. Any help would be appreciated.</p>
        </script>
    </html>

Answer №1

all_markers.push(marker) is placed outside of the conditional block where you assign a marker to the marker variable, resulting in pushing an undefined variable multiple times.

L.featureGroup(all_markers) does not accept an array with undefined keys, leading to the error message.

To fix this, simply move the first instruction inside your if condition:

if (rec.descriptor.indexOf(noise_description[i]) > -1) {
    console.log(rec.descriptor);
    marker = L.marker([rec.latitude, rec.longitude]);
    markers[i].push(marker);
    all_markers.push(marker);
    break;
}

In addition, there is a typo in overlay[noise_description[i]]: it should be overlays[noise_description[i]].

Check out the demonstration here: http://jsfiddle.net/ve2huzxw/55/

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

Divide an Array into multiple String elements using JavaScript

Here is my array: ["John Connor ", "Mike ", "Ryan Jones ", "Markey O ", "Markey B"] I want to display each of these elements as separate strings, one below the other on the page. I tried using $(".info_container").text(myArray); but that just displayed t ...

Troubleshooting issue with ng-hide in AngularJS when using multiple filters

I'm struggling to implement two filters using ng-hide. Check out this fiddle where I've showcased the issue: http://jsfiddle.net/czPf6/2/ I have a piece of code that dynamically selects which filter to use based on input values from an input box ...

Creating a jQuery AJAX call with a vanilla JavaScript promise

I recently transitioned my website to a Single Page Application (SPA), which involves working with only one HTML page populated using JavaScript. In order to simplify the process, I decided to consolidate my JavaScript files into one. However, while creati ...

What is the best way to display text from one text field onto another text field?

Here's a challenging question that I've been pondering... Issue: I am using a virtual keyboard that needs to interact with different text fields on various pages. Every time I click on a text field, the keyboard should appear, and every key I pr ...

Ryan Fait's Code for Creating a Responsive Sticky Footer Height

There are quite a few queries regarding Ryan Fait's sticky footer, but I urge you not to dismiss this one immediately! My goal is to have a footer with a dynamically sized height that sticks to the bottom of the page. Ryan Fait suggests wrapping all ...

Despite encountering an error in my terminal, my web application is still functioning properly

My code for the page is showing an error, particularly on the home route where I attempted to link another compose page The error message reads as follows: Server started on port 3000 Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after t at new Node ...

To convert an image file into a string, use JSON.stringify before including it in an AJAX request

Is it possible to send image files contained within JSON objects in an array via an AJAX call using JSON.stringify? When attempting to send the data through an AJAX call, and utilizing JSON.stringify with an array containing JSON objects that have image f ...

What are the reasons for the dynamic exclusion of an element in Angular?

Can someone help me figure out why my data is not being added dynamically using ng-repeat? I have entered the "name" which should be added to the data, but it is not displaying in the UI. You can see the issue in this demo app.controller("studentcntr", ...

Using postMessage with an iframe is causing issues within a React application

I encountered two errors when executing the code below in my React application: try { iframe.src = applicationRoutes.href; iframe.style.width = '0px'; iframe.style.height = '0px'; iframe.style.border = '0px& ...

How to retrieve the hidden parameter value stored within a div element with jQuery

Within the mainDiv, there is a hidden field with the class name "myHiddenField". I am looking to retrieve the value of this hidden parameter by using jQuery. I attempted: $("#mainDiv .myHiddenField").val() as well as $("#mainDiv .myHiddenField").attr( ...

AgGrid supports multi-line content within its cells

I attempted to utilize this solution, however, it is not functioning properly for me. While it does resize the column height correctly, the text is still not wrapped as expected. Ag-Grid - Row with multiline text let gridOptions = { columnDefs: column ...

Internet Explorer 11 XHR Troubles

Our company has successfully developed a JavaScript video player that can be embedded on various websites using a script tag. As part of the bootstrapping process, we utilize XMLHttpRequest to fetch resources from our server. This creates cross-origin requ ...

Google uploader selector

I am currently working on implementing a Google Drive picker that allows me to upload new local files to my Drive. The picker is functional and displaying my existing Google Drive files, but I am unable to find an "upload" button, even after adding the goo ...

How can I successfully filter a nested array in javascript using values from the array in order to also make it compatible with single values?

In exploring this issue further, I discovered an interesting example from a different topic. This example involves filtering a nested array within another array based on specified filter values. Curiously, the method used in this example doesn't work ...

Tips for sorting data by date range in MongoDB

[{ "_id": { "$oid": "5d7a76c94c3c8c05618cef58" }, "title": "hello", "date": { "$date": "2019-06-07T07:22:00.000Z" }, "__v": 0 }, { "_id": { "$oid": "5d7a7809ef31980615ed3756" }, "title": "hello", ...

Nodes are currently being loaded in the JIT SpaceTree

I am currently trying to implement the SpaceTree from JIT and I could really use some assistance. The issue arises when I attempt to load the tree from another array. json.php <?php $temp = array( 'id' => "node02", 'name&apos ...

The navigation located at the top rather than in the header

I want the navigation in my HTML file to be visible at the top so that users can scroll up to see the header. Do you understand what I'm trying to achieve? I will provide visual examples with 2 images. PS: I prefer not to use hashtags as they are al ...

What is preventing me from extracting the callback function from the app.get method in Node.js and Express?

In my server.js file, I'm attempting to do the following: // This code is not functioning as expected, and I am unsure why. var findBooks = function (err, books) { if (!err) { return response.send(books); } else { console.log( ...

Node.js not resetting array properly

I have successfully set up a Node+Express API that is working smoothly, but I am facing an issue with returning responses for complex queries. The problem lies in the fact that the variable where I store the response data is not being reset between differe ...

Vue fails to reflect changes in data when it is updated

I have a page where I can access data by calling domain.com/subpage?soundfile=something Using the fetch method, I extract the query parameter from the URL to retrieve the necessary information. The retrieval process is successful as indicated by the data ...