Leverage the leaflet search plugin alongside the $GetJson functionality

My request is to make the leaflet search plugin functional with an external .json file connected to the map.

To elaborate on my goal, I will provide two code examples:

The first one is sourced from an offline file with a geoJSON js file attached:


var sitis = L.geoJSON(sitec, {
pointToLayer: function (feature, latlng) {
feature.properties.myKey = feature.properties.Title + ', ' + feature.properties.Head;
return L.circleMarker(latlng, geojsonMarkerOptions);
},
onEachFeature: function (feature, layer) {
layer.bindPopup("<h1><u><font color='red'>" + feature.properties.Title + "</h1></u></font><h2>Address: " + feature.properties.Head + "</h2><p>" + feature.properties.Description + "</p><p> Website:" + feature.properties.URL + "</p><br><center><a href='file:///Z:\\Fixed Line\\Design & Build\\2. Clients\\Openreach\\3. MDU Designs\\Coventry\\OR66 - Priory Court, Coventry\\20190709_121215019_iOS%20(1).jpg' target='blank'><img src='images/" + feature.properties.Pict + "' style='width:200px;height:300x;'></a>");
}
}).addTo(map);

The leaflet search works perfectly with the above code.


L.control.search({
layer: L.layerGroup ([sitis, church]),
initial: false,
propertyName: 'myKey',
zoom: 14,
position: 'topleft'
})
.addTo(map);

L.control.scale({
position: 'bottomright',
})
.addTo(map);

However, the second code has encountered an issue.

The initial data for the second code is as follows:


$.getJSON(url1, function(data) {

job = L.geoJson(data, {

pointToLayer: function(feature, latlng) {
return L.circleMarker(latlng, {
radius:6,
opacity: .5,
color:getColor(feature.properties.League),
fillColor: getColor(feature.properties.League),
fillOpacity: 0.8
});
},

onEachFeature: function (feature, layer) {
layer._leaflet_id = feature.properties.Owner;

var popupContent = "<p>The <b>" +
feature.properties.Owner + "</b> play here,</br> They are in the " +
feature.properties.League + "</br>" +
'<a href="'+ feature.properties.Website +'" target="_blank">Website</a></p>';

if (feature.properties && feature.properties.popupContent) {
popupContent += feature.properties.popupContent;
}
layer.bindPopup(popupContent);

}
}).addTo(map);
});

I attempted to implement the leaflet search control using the following code:


L.control.search({
layer: L.layerGroup ([job, job2, job3]),
initial: false,
propertyName: 'Owner',
zoom: 18,
position: 'bottomright'
})
.addTo(map);

But unfortunately, the search functionality did not work as expected, and the console displayed an error message.

Links to possible solutions have been provided:

https://medium.com/@maptastik/loading-external-geojson-a-nother-way-to-do-it-with-jquery-c72ae3b41c01

https://jsfiddle.net/expedio/7e8b6gyu/

If you can help me resolve this issue and enable the leaflet search feature for an external .json file fetched via $GetJSON function, it would be greatly appreciated.

Answer №1

To improve functionality, a possible solution involves embedding the L.Search.Control within the $GetJSON function block, creating a distinct "body" within the primary script. The revised code snippet demonstrating this resolution is as follows:

var url1 = "Peterborough.json"; //.json file containing the data
var job; //variable to hold our layer

$.getJSON(url1, function(data) {
job = L.geoJson(data, {

    pointToLayer: function(feature, latlng) {

        return L.circleMarker(latlng, {
        radius:6,
        opacity: .5,
        color:getColor(feature.properties.League),
        fillColor:  getColor(feature.properties.League),
        fillOpacity: 0.8

        });
    },

        onEachFeature: function (feature, layer) {
            layer._leaflet_id = feature.properties.Owner;


            var popupContent = "<p>The <b>" +
            feature.properties.Owner + "</b> play here,</br> They are in the " +
            feature.properties.League + "</br>" +
            '<a href="'+ feature.properties.Directory +'" target="_blank">Local 
 directory</a></p>' ;

            if (feature.properties && feature.properties.popupContent) {
                popupContent += feature.properties.popupContent;
            }
                layer.bindPopup(popupContent);

        }

        }).addData(data).addTo(map);
        
        //Integrating leaflet-search plugin inside the $GetJSON function
        L.control.search({
layer: job,
initial: false,
propertyName: 'Owner', //Specifies the property to search for
zoom: 18,
position: 'topleft'
  }).addTo(map);

}); //End of $GetJSON function scope

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

Prevent keypress from being detected while the confirm box is displayed

My website heavily relies on key events, and for certain actions, it triggers a bootbox confirm box. This confirm box appears over a transparent layer, blocking all mouse click actions unless the user interacts with the confirm box. Now, I also want to dis ...

Upon clicking the <p:submenu> element, directly navigate to the first <p:menuitem> element

I am working with a dynamic <p:menubar> as shown below: <p:menubar style="position: relative; height: 30px; visibility: visible;"> <p:submenu label="Category" icon="ui-icon-document" styleClass="mainMenu"> <c:forEach var=" ...

Utilize Object.keys and Object.values to transform a JSON object into a ChartJS representation

I have a unique JSON file structure that I am trying to display in ChartJS. The data looks like this: { "AAPL": [ { "Q1": -26986, "Q2": -168099, "Q3": -137101, "Q4": -5 ...

Add attributes to the top level

<li class="page_item"><a href="javascript:">A</a> <ul class="children"> <li class="page_item"><a href="">1</a></li> <li class="page_item"><a href="">2</a></li> </ul> < ...

Error message encountered when attempting to export functions in Reactjs, resulting in an undefined function error in the context of Reactjs

As I work on creating an adaptive menu using Reactjs and Material UI, I have managed to complete everything. However, I encountered an issue when trying to import a const defined in a different file as the functions are not functioning as expected. The fu ...

Toggle the sliding menu drawer option (upward/downward motion)

When it comes to my simple menu, I'm using jQuery to toggle the visibility of a few DIVs. The code is straightforward as shown below, and I could really use some assistance with adding extra functionalities. <div id="one" class="navLinks"> cont ...

Choosing the parent folder that is at least two levels above in JavaScript

My directory structure is: /project Login |1.1 js |1.2 db Main Within the 'db' folder, there is a script that utilizes AJAX to determine if a user is an admin or regular user. The goal is to redirect to a page stored in the 'Main&apo ...

Infinite scroll causing Firebase ".length" function malfunction

My NextJs website is encountering errors related to Firebase infinite scroll. The issue seems to be with the .length property being undefined for some unknown reason. I am struggling to debug the code and make it work properly in Next.js. Any help would be ...

Verifying X-editable input in Laravel (Server-side)

I've successfully integrated x-editable into my webpage (). When I click on a field, it becomes editable inline, allowing me to make changes and submit them to a POST URI. Currently, I am sending three key-value pairs: array:3 [▼ "name" => "n ...

Navigating between Vue Router pages triggers multiple events within the mounted() lifecycle of VueJS

Currently, I am immersed in a project using Electron with a Vue CLI setup and the Vue CLI Plugin Electron Builder. The overall functionality is working perfectly fine except for a peculiar bug that has recently surfaced. The issue arises when navigating b ...

Creating a tree structure in Node.js using JSON data while preventing duplicates: A step-by-step guide

My MongoDB has some JSON data that looks like this: [ { "_id": { "$oid": "1" }, "name": "A Inc", "children": [ {"$oid": "2"},{"$oid": & ...

Exploring the capabilities of querying Django models with JSONField using the values() method

In my Django application using a Postgres database, I have JSON fields within my model that I am in the process of switching from char based to jsonb fields. This allows me to easily filter on a key within the field. However, I'm wondering if there is ...

Displaying a specific fieldset based on the radio button selection

I have created a form to handle user input using PHP, with the initial question prompting the user to choose from three radio buttons for the "type" parameter - the options being "book", "journal", and "website". Here is what the code looks like: <stro ...

Conceal a div when the user is browsing within a Facebook page tab

I am trying to create a webpage that can be accessed directly or through a Facebook page tab. My goal is to only display a Facebook logo if the user is accessing the page outside of Facebook. If they are already viewing the page within Facebook, I don&ap ...

Is it possible to change the hover highlight rotation on a link without affecting the surrounding elements?

Is it possible to rotate the highlight on a link when hovered? I'm new at this, so apologies if this question seems basic. This is how my css/html is currently structured: .links { display: block; } .links a { color: #000000; text-decoratio ...

What is the best way to change the date format in the GET API response for all objects

Recently started working with Angular, I'm receiving object data from an API call. data= [ { "Id": 4, "IssueDate": "2021-01-25T15:17:00.85", "ExpiryDate": "2021-01-25T15:25:40.263" ...

mention colleague(parent) instruction request

I have been exploring the use of metadata for setting HTML input attributes. After reading through the Attribute Directives Guide (https://angular.io/docs/ts/latest/guide/attribute-directives.html), I have developed the following implementation: import "r ...

What is the process for invoking a NodeJS script within a personalized VSCode Extension?

Recently, I created a NodeJS script for one of my projects and now I'm looking to develop a VSCode extension around it. How can I integrate this script as a command within my custom extension? The goal is to have the script packaged along with the e ...

I'm experiencing some unexpected behavior in JavaScript when I try to apply style changes using JavaScript. Is it possible that transitions are not occurring in both cases as expected?

Everything seems to be working fine with the transition, but when I skip using setTimeout and directly apply the transform, the div instantly reaches the end of the transition. function move(x, y, delay) { let el = document.getElementById('myDiv& ...

Trying out the demonstration of the angular calendar in action

I am currently attempting to run the official example of the angular-calendar component found at http://angular-ui.github.io/ui-calendar/ Unfortunately, I am encountering an error that states: TypeError: undefined is not a function - it seems that the fun ...