Utilizing JSON instead of GeoJSON with AJAX in Leaflet

I am in search of a method to utilize JSON instead of GeoJSON with leaflet, making use of AJAX. The use of JSON and AJAX is imperative for this task.

I have successfully called a JSON file using AJAX. However, I am now unsure about how to effectively utilize the data from the JSON to plot markers on the map. It seems like using L.geoJson() may not be the solution in this case.

Here is the HTML code snippet:

<div id="map" style="width: 800px; height: 500px"></div>

This is the JavaScript file:

var map;
var overlay;

var addPopupsFromLocations = function(locations) {
  var popups = new Array();
  locations.forEach(function(location){
    console.log('creating popup for location ' + location.title);

    console.log(location.latitude);
    console.log(location.longitude);
      });
};

function init() {
        var map = L.map('map').setView([51.505, -0.09], 13);

        L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
            maxZoom: 18,
            attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
                '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
                'Imagery © <a href="http://mapbox.com">Mapbox</a>',
            id: 'examples.map-i86knfo3'
        }).addTo(map);
    }

$(document).ready(function(){
    init();
    $.ajax('locations.json', {
        dataType: 'json',
        success: addPopupsFromLocations,
        error: function(xhr, st, et) {
          console.warn(et);
        }
    });
});

This is the JSON file:

[
  {
    "title": "Weathertop",
    "link": "http://en.wikipedia.org/wiki/Weathertop",
    "latitude": 51.505,
    "longitude": -0.09,
    "imageUrl": "assets/img/location-images/Weathertop.jpg"
  },
{
  "title": "Rivendell",
  "link": "http://lotr.wikia.com/wiki/Rivendell",
  "latitude": -0.09,
  "longitude": 51.505,
  "imageUrl": "assets/img/location-images/Rivendell2.jpg"
},
{
  "title": "Minas Tirith",
  "link": "http://lotr.wikia.com/wiki/Minas_Tirith",
  "latitude": 38.78,
  "longitude": -77.18,
  "imageUrl": "assets/img/location-images/320px-Minas_Tirith.jpg"
}

]

Console:

creating popup for location Weathertop
custom.js (line 7)
51.505
custom.js (line 9)
-0.09
custom.js (line 10)
creating popup for location Rivendell
custom.js (line 7)
-0.09
custom.js (line 9)
51.505
custom.js (line 10)
creating popup for location Minas Tirith
custom.js (line 7)
38.78
custom.js (line 9)
-77.18

Answer №1

I am exploring ways to integrate JSON instead of GeoJSON into leaflet using AJAX requests.

Let's clarify some terms:

  • JSON serves as a standard data interchange format without any specific structure.
  • GeoJSON, on the other hand, is a subset of JSON specifically designed for mapping applications like Leaflet.

If you aim to utilize L.geoJson, you must transform your data to adhere to the GeoJSON guidelines. This can be achieved through basic JavaScript manipulation.

var geojsonFormattedLocations = locations.map(function(location) {
    return {
        type: 'Feature',
        geometry: {
            type: 'Point',
            coordinates: [location.longitude, location.latitude]
        },
        properties: {
            location
        }
    };
});

Answer №2

Although it may be a delayed response, there is indeed a way to utilize a basic JSON format with Leaflet.

Upon receiving the JSON data via ajax, you can execute a function that iterates through each object within the JSON and adds a marker on the map accordingly. Here's an example:

var responseData = request.responseText;
var dataArray = JSON.parse(responseData);

for (var index=0; index<dataArray.length; index++) {
    L.marker([dataArray[index].latitude, dataArray[index].longitude]).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

Retrieving values from a multidimensional array in JavaScript

I need some help with my code. I am struggling to pass an array (larray3) containing elements from two other arrays (larray1 and larray2) from data.js to model.js and view.js. Despite correctly building the multidimensional array in data.js, when I receive ...

Prevent premature termination of slow HTTP requests in Node.js/Express server

Having an issue with long duration http requests in my React/Nodejs application. Whenever a request takes more than 4 minutes to respond, it gets aborted before reaching the client. Could there be a timeout setting for requests or something else I am overl ...

How can I pre-fill an AutoModelSelect2Field with static information in Django using the django-select2 library?

I am currently using a field similar to the one below: class ContactSelect(AutoModelSelect2Field): queryset = Contact.objects.all() search_fields = ['name__contains'] to_field = 'name' widget = AutoHeavySelect2Widget W ...

Retrieve a specific nested key using its name

I am working with the following structure: const config = { modules: [ { debug: true }, { test: false } ] } My goal is to create a function that can provide the status of a specific module. For example: getStatus("debug") While I can access the array ...

Guide on transforming json into a string using php

I am looking to convert JSON data into a String using PHP. Below is the JSON data that I have: { "": [{ "description": "hello, this is description speaking" }, { "fieldName": "myfile", "originalFilen ...

The metallic material in Substance Painter appears as a dark shade in A-Frame

After exporting an object as gltf from Substance Painter, I am importing it into my A-frame scene. Strangely, the metallic outer material appears dark in my current scene while other materials like plastic appear white and are visible. Despite already ha ...

Ways to create a smooth transition in element height without a known fixed target height

Is it possible to create a smooth height transition for an element when the target height is unknown? Replacing height: unset with height: 100px allows the animation to work, but this presents a problem as the height needs to be based on content and may v ...

Issues with the Node Package Manager's watch command functionality

Having installed the frontend dependency in my Vue.js project, I attempted to run the command npm run watch. I updated the scripts section in package.json as shown below- "scripts": { "dev": "npm run development", &qu ...

When the search button is clicked to find a specific address, the React Google Maps API fails to zoom in on

How can we modify this code to achieve the functionality where, upon clicking the search button, the map zooms in closer to the address entered by the user, similar to how it works on Google Maps? The goal is to replicate the search feature from the Goog ...

Click event inside a repeat loop

Working with AngularJS, I have a collection of colors that each have a specific title and type. These colors are displayed in a list format on the webpage. Now, I am looking to enhance this by incorporating a menu option that allows users to filter and vi ...

Add an image to a div element and determine its height, then apply the height to the CSS property

Here is my JavaScript code that utilizes jQuery: $(".article_big_photo").click(function() { $('#screen').css({ opacity: 0.5, 'width':$(document).width(),'height':$(document).height()}); $('#screen').show() ...

Examining the differences between CSV and JSON formats

If I have two CSV files, with File 1 containing standard CSV data and File 2 being a mapping file of File 1 to JSON, my goal is to map these files together and compare the data in File 1 with the JSON. The output should be any mismatches as a CSV file. Ho ...

Guide to obtaining ngPrime autocomplete text when the button is clicked within Angular 6

I am currently utilizing the ngPrime autocomplete feature to retrieve data from a service. My goal is to capture the text entered in the autocomplete field whenever a button is clicked. I attempted to access the value using getElementById.value within th ...

Morgan middleware in Express.js specifically targeting unsuccessful requests for logging purposes

Currently, I am facing an issue with my middleware setup in Express.js while using Morgan. The problem arises because Morgan is only logging requests that return error code 302 (redirected), which happens when my middleware encounters an error and redirect ...

Encountered an Unhandled Rejection error in React due to SyntaxError: Unexpected token '<' found in JSON at position

Every time I attempt to access the global variable from a different component, specifically when I try to use it from Brewery.js in Random.js, I encounter the "Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0" error. Brewery. ...

Why do we recreate API responses using JEST?

I've been diving into JavaScript testing and have come across some confusion when it comes to mocking API calls. Most tutorials I've seen demonstrate mocking API calls for unit or integration testing, like this one: https://jestjs.io/docs/en/tuto ...

Adding a JObject collection into SQL Server using Dapper

How can I successfully insert the result of my JObject into an SQL Database when I keep getting an error about not being allowed to insert arrays or lists? What am I missing in my code? Below is the code snippet I have been working with so far: JArray j ...

How to retrieve element from templateUrl in AngularJS controller

I am facing a challenge in populating select(option) element inside a template html file from the controller. Although I have managed to do it successfully, I am unable to set a default value to avoid the initial empty option. Here is a snippet from the t ...

Ways to avoid Parents Click Event from triggering during a Child's (Grandchild's) click event

My parent div has a unique feature where clicking on it reveals one of the child divs, and clicking again toggles the visibility of the child div. Inside this child div, there is a switch toggle that functions as a hidden checkbox. The issue I'm facin ...

Unable to alter state from the onClick event of a dialog button

In the process of developing a Next.js app, I encountered an interesting challenge within one of the components involving a DropdownMenu that triggers a DialogAlert (both powered by Shadcn components). The issue arises when attempting to manage the dialog& ...