Incorporating City Capital Icons onto a Leaflet Map with JavaScript Integration

I've set up a layer on my leaflet map and have a capitalCities.js file that contains data for markers I want to add to the map. Here's a snippet from the capitalCities file:

let capitals = [{"CountryName":"Somaliland","CapitalName":"Hargeisa","CapitalLatitude":"9.55","CapitalLongitude":"44.050000","CountryCode":"NULL","ContinentName":"Africa"},{"CountryName":"South Georgia and South Sandwich Islands","CapitalName":"King Edward Point","CapitalLatitude":"-54.283333","CapitalLongitude":"-36.500000","CountryCode":"GS","ContinentName":"Antarctica"},{"CountryName":"French Southern and Antarctic Lands","CapitalName":"Port-aux-Français","CapitalLatitude":"-49.35","CapitalLongitude":"70.216667","CountryCode":"TF","ContinentName":"Antarctica"}];

I'm trying to figure out the best approach for adding these markers to the map. I've been considering using an ajax request like the one below, but I'm struggling with how to integrate it with the leaflet layers map. So far, this is what I have in my JS file:

let capitalCityLat; let capitalCityLon;

This is the ajax request I'm currently working with:

 $.ajax({
      url: "js/capitalCities.js",
      type: 'POST',
      dataType: 'json',
      data: {
          capital: $('CapitalLatitude', 'CapitalLongitude' ).val()   
      },
      success: function(result) {

Any advice or guidance would be greatly appreciated.

Thank You

Answer №1

If you want to easily add a marker to a Leaflet map, you can simply use the following code:

L.marker([50.84673, 4.35247]).addTo(map);

In your specific scenario, where you need to add markers based on information in the capitals array, you could try something like this:

let capitals = [{"CountryName":"Somaliland","CapitalName":"Hargeisa","CapitalLatitude":"9.55","CapitalLongitude":"44.050000","CountryCode":"NULL","ContinentName":"Africa"},{"CountryName":"South Georgia and South Sandwich Islands","CapitalName":"King Edward Point","CapitalLatitude":"-54.283333","CapitalLongitude":"-36.500000","CountryCode":"GS","ContinentName":"Antarctica"},{"CountryName":"French Southern and Antarctic Lands","CapitalName":"Port-aux-Français","CapitalLatitude":"-49.35","CapitalLongitude":"70.216667","CountryCode":"TF","ContinentName":"Antarctica"}];


capitals.forEach(capital => {
   L.marker([capital.CapitalLatitude, capital.CapitalLongitude]).addTo(map);
})

If you are worried about accessing the capitals array from another file, you can include a reference to that file in your index.html using

<script src="js/capitals.js"></script>
.

The capitals variable will then be accessible globally in other scripts as well.

Check out this example too: https://codepen.io/dhruvs/pen/jOwVXKv

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

Can I retrieve plain text instead of HTML from a server side error in ASP.NET MVC on an ajax request?

When I return a HttpException() from an ajax call, I notice that I receive a large amount of HTML text. If I have something like this in my controller: if (errors.Count > 0) { throw new HttpException(404, "This is my custom erro ...

Tips for optimizing AJAX content for Google indexing

As I begin the process of developing a public website that utilizes client-side rendering with AngularJS, I have come across information suggesting that dynamically generated content may not be properly indexed by Google. This raises concerns about the imp ...

When the datatype is specified, $.post fails to function

I have encountered an issue with the following code. When I remove , "json"); from the end, it seems to work but only results in a failure. Despite referring to the jQuery specs on their website, I am unable to identify why the $.post method is not functio ...

Spin everything around, even the camera, without relying on the orbit controller in THREE.JS

My goal is to rotate everything on the scene, including the camera, when a specific condition is met. The rotation should be seamless for the user, with the camera still showing the same view even though the objects have been rotated. I want to ensure th ...

What is the best way to preserve a user's role using AJAX?

My application involves two models, User and Role, along with a pivot table. Currently, my controller displays the roles that a user has in checkboxes. How can I ensure that the selected roles are stored in the database? Also, how do I write the AJAX code ...

The electron program is unable to locate the package.json module

I am new to electron and attempting to run an express app for the first time. However, I encountered this error: Need assistance updating code Error: Cannot find module 'C:\package.json' at Module._resolveFilename (module.js:440:15) ...

Clear the local storage once the URL's view has been fully loaded

When retrieving details of a specific item by passing URL parameters stored in local storage, I encountered an issue. I need to delete the local storage variables after the view is loaded. However, what actually happens is that the local storage variable ...

Tips on discovering the initial and/or final timestamp of a set interval function as it triggers or reaches completion

My goal is to create a script in Tampermonkey for a frequently visited website, specifically to track the movements of my ships. The website generates a table displaying the current movements, with code structured like this: <table class="movements_tab ...

Updating a web page in Node.js with Express when new data is added to the database

I've managed to set up messaging on my website, but I want the recipient to see messages in real-time without needing to refresh the page. It would be neat if a notification or badge appeared for the user when they receive a new message. As a beginn ...

Struggling to retrieve an element from an object received through a get request in Express

I am facing an issue with a get request that returns an array of objects retrieved from a database using Knex. I am trying to use .map to make these objects accessible, but I am struggling with accessing the final element which is a sum(). It seems like a ...

Modifying several classes across different elements within a Svelte component

I developed a simple quiz application in which the user selects an answer and then clicks the 'check' button. If the selected answer is correct, it will be highlighted in green while incorrect answers are highlighted in red. Conversely, if the wr ...

Scenario-specific blueprints

I'm currently facing a challenge in incorporating logic into a dustjs template, and I find it challenging to integrate all the components seamlessly. Here is an example of the JSON data I have: { "names": [{ "name": "User 1", "is ...

The prototype object of the Datatable request parameter is missing

When attempting to make a datatable ajax request, I encountered an unexpected result on the server side. The console is logging the data as shown below: [Object: null prototype] { draw: '1', 'columns[0][data]': 'no', &ap ...

Utilizing Algolia search hits in conjunction with React Router: A guide

I'm currently utilizing Algolia’s react instant search feature, and I’m seeking guidance on how to implement a code snippet that will direct me to a designated page when a "hit" from the hits widget is clicked. My project is built using Next.js. ...

What is the process for validating a web2py form submitted through AJAX?

I am attempting to send a form using web2py's ajax function as detailed in the book, but I am utilizing FORM instead of SQLFORM because I do not want the data to be saved in a database. ajax_test.html {{extend "layout.html"}} <h2>Form</h2&g ...

Error: The call stack has exceeded the maximum size limit (jquery-1.12.4)

Currently attempting to implement a feature that allows users to upload an image file with a preview using Jquery. While I successfully managed to display the preview, clicking on the upload button triggered an error message. An unhandled RangeError occ ...

What steps can I take to address the problem in iOS 17 where sound is coming from the earpiece instead of the speaker during camera activation?

I have a Progressive Web App where I use the getUserMedia() API to access the camera and HTML audio tags for handling media content. However, ever since updating to iOS 17, I've faced an issue where audio plays through the earpiece instead of the medi ...

Sending data from local storage to ajax call

Below is the code snippet in question: $.ajax({ url: localStorage.getItem("isntagram link"), // url: "https://api.instagram.com/v1/users/self/feed?access_token=233291163.8a612cd.c49f77de073746e9a2f53116b720302e", met ...

"Adding an Image within a Textbox Using Ext JS: A Step-by-Step

How can I add a search image inside a textbox created with the following code? I have created a table with a footer, and within one of the textboxes in the table, I want to include a search button that will call another function when clicked. However, desp ...

React Resize Detection: Handling Window Resize Events

Is there a more efficient way to listen for the window resize event in react.js without causing multiple callbacks? Perhaps a React-oriented approach (like using a hook) to achieve this? const resizeQuery = () => { console.log("check"); if ( ...