Iterate through the .json file and add markers to a leaflet map

Apologies for the basic question, but I'm struggling with understanding JavaScript and json files. I have a .json file that updates server object locations every 5 seconds, and I want to plot these coordinates on a map using leaflet for staff access.

Currently, I've used PHP to decode the json file, extract the coordinates, and plot markers on the map. However, I'd like to implement live marker updates without refreshing the page when the json file changes.

This is the PHP code I'm currently using:

<?php
$count = 0;
$str = file_get_contents('coords.json');
$json = json_decode($str, true);

foreach($json['coords'] as $coords)  {
  $count++;
  ${'yCord_'.$count} = $coords['y'];
  ${'xCord_'.$count} = $coords['x'];
};

for ($i = 1; $i <= $count; $i++) {
  echo  "L.marker([" . ${'xCord_'.$i} . "," . ${'yCord_'.$i} . "], {icon: icon_door}).addTo(map);";
}
?>

However, after researching, it seems updating live with just PHP isn't possible, so I've started working on a solution using JS. Here's what I have so far:

$.getJSON( "coords.json", function(json1) {

     for (var i = 0; i < json1.coords.length; i++) {
        var place = json1[i];

        // Creating a marker and putting it on the map
        var customIcon = L.icon({
            iconUrl: 'https://leafletjs.com/examples/custom-icons/leaf-green.png',
            iconSize:     [38, 40],
            iconAnchor:   [10, 40],
            popupAnchor:  [5, -40]
        });
        var marker = L.marker([place.x, place.y], {icon: customIcon});
    }

});

It seems I'm having trouble extracting specific data from my json file, as other examples I've found online have different structures. My json file (coords.json) looks like this:

{
    "coords": {
        "1": {
            "x": 21249,
            "y": 7135
        },
        "2": {
            "x": 21249,
            "y": 7125
        },
        "3": {
            "x": 21244,
            "y": 7140
        }
    }
}

The number of coordinates in the json file may vary depending on the number of objects. Any guidance would be greatly appreciated.

Answer №1

I finally solved the problem! For those who are interested in my solution, here it is:

 $.getJSON( "coords.json", function(json1) {
   for(var key in json1.coords){
     var latLng = L.latLng([json1.coords[key].x, json1.coords[key].y]);
     L.marker(latLng, {icon: enciv}).addTo(map);
   }
 });

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

Tips for parsing form values using jQuery AJAX:

Is there a way to extract form values and check if 15 objects have values or not? I attempted to do this using jQuery.parseJSON() but it didn't work as expected. [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Obj ...

Is there a way for me to extract text from a leaflet popup in order to generate the complete URL for an AJAX request?

When text within a popup is clicked, I want to trigger an ajax call. The content in the leaflet popup has been set previously by another ajax call. Below is the JavaScript code for both ajax calls: $("#button").click(function() { var name = document. ...

Transform the terraform resource data, which is in the form of a map containing keys of type string

I am currently developing a custom terraform provider and have encountered an issue. I'm attempting to convert a schema.TypeList field into a struct. Here is what the TypeList looks like: "template": { Type: schema.TypeLi ...

MVC3 does not support JQuery UI

Just recently, I had all my jquery-ui elements functioning perfectly. However, now it seems that none of the jquery-ui features are working anymore. In my Site.Master page, I have included the following code... <link href="../../Content/Site.css" rel=" ...

Manipulating a DOM element in Angular 2 to alter its class attribute

I am a beginner in angular2. Here is my code: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'main', template: ` <div class="current"> </div> ` }) export class MainComponent impl ...

What could be the reason for receiving a Firebase INVALID_DYNAMIC_LINK_DOMAIN error message?

I'm having trouble implementing email verification in my React website. Whenever I use the sendSignInLinkToEmail function, I encounter the following error: XHRPOSThttps://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=xxxxxxxxxxxxxxxxxxx [ ...

Is there a way to filter out only the objects from the JSON data and exclude the strings?

I am facing an issue while looping through a JSON object. The presence of strings in the JSON is causing the loop to fail. How can I iterate only through the objects in the JSON without affecting the loop? My main goal is to iterate through the objects co ...

Error: Unexpectedly encountered a nil value when trying to unwrap an Optional value // Attempted to access a key "items" in the JSON dictionary

I encountered an issue with the JSON data before, but managed to resolve it based on a suggestion from alexcurylo in this link: Ambiguous use of 'subscript' with NSArray & JSON Initially, everything was functioning correctly. However, I am no ...

Docker: CORS policy is blocking access to XMLHttpRequest

After creating an ASP.NET Web Application (.NET Framework) project in Visual Studio 2022 and adding a web service to it, everything seemed to work fine when testing the web service call on Local IIS. However, things took a different turn when I tried runni ...

Incorporate pug and sass into your React project for a more

Are pug/jade and sass compatible with react? I enjoy organizing my code by separating files, and the functionality that sass and pug provide is great for this purpose. Is there a way to integrate pug and sass into a react project? Pug example: doctype ...

a guide to transforming data into a string with json using angular

I am struggling to figure out how to bind my form data into a JSON string. My situation involves using a string field in the database and saving checkbox values in a single database column using JSON. I have created an HTML form, but I am unsure of how to ...

Building Individual Elements in Angular 2

My task involves creating two distinct components in Angular 2, the Users component and the Clients component. These components are not nested and do not have any relationship. To call these components separately, I typically use main.ts as the main entry ...

Updating data in Redux triggers a refresh of Material UI table data

Utilizing the material-ui data table component to showcase data, enabling users to update and save information via a form when clicking on a row. Implemented react-redux for state management and dispatching updated rows to the existing data. However, despi ...

Customizing Gunicorn's log file format

Looking to deploy Flask with Gunicorn on Kubernetes and aiming to have all logs output in JSON format for proper logging. Experimenting with Minikube and trying out https://github.com/inovex/kubernetes-logging to utilize Fluentd for log collection. Succe ...

Cookie Strategy for Managing Popups Site-wide

Below is a script that will trigger a popup after 60 seconds of page load. This script also creates a cookie to prevent the popup from appearing more than once. The cookie expires when the user's session ends. However, the popup only appears on the e ...

What is the process for accessing npm packages through a website?

Recently, I've been delving into the realm of Node.js and attempting to configure a specific Node.js package created by Uber. Despite my limited experience with Node.js, I rigorously followed these steps: Initiated cloning their repository from here ...

Identifying Flash content in a unique way

In my dynamic page (let's call it myFlashContainer.jsp), the Flash content changes based on the link that is clicked. The code responsible for rendering the Flash looks like this: <object height="100%" align="l" width="100%" id="player" codebase= ...

Randomize elements with the click of a button

Every time the page refreshes, the words shuffle around. For instance, "May I# know# your name?" shuffles to "know May I your name". To display the correct sentence with "#" as "May I know your name?", click the SHUFFLE button to trigger the shuffling. HT ...

Unable to access static library Java Script file path using NSBundle

I have integrated a static compiled library into my project, which includes a JavaScript resource. At a specific event in my app, I need to execute the JavaScript file from this library. However, I am facing an issue where the path to the JS file appears ...

Javascript - issue with accurately retrieving element offset value while scrolling

My goal is to dynamically change classes for elements based on their position during scrolling. I am trying to calculate the top offset element value and adjust the classes accordingly. Here is the function I am using: handleScroll () { const header = ...