Creating a marker with input from a pop-up form in Leaflet: A step-by-step guide

I'm new to JavaScript and I'm struggling to figure out a solution to this problem.

I want a form to appear when the user clicks on the map. After filling out the form, I want to create a marker at that location with the popup content set to the values from the form. Additionally, I need to send the form data to a database once the user has finished adding forms.

The form itself is working fine, but I'm having trouble accessing the popup location data from the function that handles the form submission.

Below you'll find the code I have so far:

function onMapClick(e) {
    popLocation = e.latlng;
    var popup = L.popup({
        closeButton: true})
        .setLatLng(e.latlng)
        .setContent(popupForm)
        .openOn(map);

     $("#popup-form").submit(function(e){
         e.preventDefault();
         console.log(e);
         var geojsonFeature = {
            "type": "Feature",
            "properties": {
                "type": $("input[name='goodBad']:checked").val(),
                "location":  L.DomUtil.get('location').value,
                "reason": L.DomUtil.get('reason').value,
                "improve": L.DomUtil.get('improve').value
            },
            "geometry": {
                "type": "Point",
                "coordinates": popLocation
            }
        };

        L.geoJson(geojsonFeature, {
            pointToLayer: function (feature, latlng) {
                marker = L.marker(geojsonFeature.geometry.coordinates, {
                    icon: L.AwesomeMarkers.icon({icon: 'info', prefix: 'fa', markerColor: markCol}),
                    riseOnHover: true,
                    draggable: true //define the content to be added to the marker
                }).bindPopup(popupForm);
                marker.on("popupopen", onPopupOpen);
                openOn(map);
                return marker;
            }
        }).addTo(map);
        map.closePopup();
     });

If you need to reference the form, here it is:

var popupForm = '<form id="popup-form" class="form-container"> \
                <h2>Add a point:</h2>\
                <strong> The air quality here is: </strong> <br> \
                <label for="type">Good</label> \
                <input type="radio" name="goodBad" value ="good" id="good"> \
                <label for="type">Bad </label> \
                <input type="radio" name="goodBad" value = "bad" id="bad"> \
                    <br><br></c> \
                <label for="location"><b>Location Name</b></label> \
                <input type="text" placeholder="eg. Redbridge flyover" id="location" > \
                <label for="reason"><b>Why are you adding this point? - be specific!</b></label> \
                <input type="text" placeholder="eg. There is a traffic jam every saturday 11am" id="reason" > \
                <label for="solution"><b>How would you improve air quality at this location? <br>(If you ran the city)</b></label> \
                <input type="text" placeholder="eg. I\'d close the road when when school starts and stops" id="improve"> \
                <button type="submit" id="btn-submit" class="btn">Save</button> \
                <input type="hidden" id= "hiddenField" name="id" value="" /> \
            </form>';

Thank you very much.

Answer №1

To tackle this problem, I recommend the following approach:

1) Display all points/markers using a geoJSON file, which we can temporarily name foobarJSON.

2) When the map is clicked, capture the coordinates of the click event.

3) Add those coordinates to foobarJSON and update the map with the new version of foobarJSON.

4) Update your database with the new coordinate.

For step 3, you can use a function like this:

function updateFeature(updatedGeoJsonData) {
  var updatedFeature = myFeaturesMap[updatedGeoJsonData.properties.objectID];
  updatedFeature.clearLayers(); 
  updatedFeature.addData(updatedGeoJsonData); 
}

Reference: In-place Update Leaflet GeoJSON feature

I hope that explanation is helpful.

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 automatically scrolling mat-select option to the top when mat-select is closed

Is there a way to automatically scroll the mat-select options to the top after closing it? I am faced with a situation where I have numerous options in my mat-select dropdown. If I select an option from the bottom and then close the mat-select, is there a ...

Is there a way to seamlessly transition the visibility of the Bootstrap 5.3 Spinner as it loads and unloads?

After delving into some research regarding Bootstrap-compatible spinners, I stumbled upon a piece of code. Take a look: function getData() { var spinner = document.getElementById("spinner"); spinner.style.display ...

Utilize the power of jQuery to easily toggle visibility of an overlay

I have successfully implemented JQuery to show and hide my overlay with great success. Now, I am interested in adding animations to enhance the user experience. After reviewing the jq documentation, I found some cool animations that can be easily integrate ...

Utilizing an Application Programming Interface in React Native

Recently diving into React Native, I embarked on creating a basic app leveraging the Marvel API along with an API wrapper. My aim is to implement an infinite scroll view using VirtualizedList. Here's where I could use some guidance: What should be pas ...

Execute unit tests for the nodejs project

Looking to execute the tests for this project on GitHub? Head over to the test folder on https://github.com/node-opcua/node-opcua. However, I'm unsure about the testing framework that was utilized and how to run all the tests. Any guidance would be mu ...

The image slideshow on W3 Schools displays images in a stacked formation

Utilizing this code snippet from W3 Schools to incorporate an image slideshow into my web project. However, upon page load/reload, the images appear stacked vertically rather than horizontally (one above and one below). The slideshow functions properly aft ...

What is the best way to end a table row after every group of four items?

I am working with a Handlebars template to display an array of movies in a table with four columns. Currently, I have set up a HBS helper in my code: app.engine('handlebars',exphbs({ defaultLayout: 'main', helpers: { n ...

What steps should I follow to integrate Semantic UI into a project using React and Express?

As a newcomer to Semantic/React/Express, I am wondering how to incorporate the stylesheet for Semantic in React. Do I need an html file that directly references the Semantic css and JavaScript files? Currently, I am not utilizing any html files. In my mai ...

Vue component encounters undefined error when passing prop array through component

My challenge is passing an array of dates to my component, but I keep encountering this error: [Vue warn]: Property or method "dates" is not defined on the instance but referenced during render I'm puzzled by this issue because I am receiving the ...

Learn the steps to modify or remove table information from a database using a webpage

Hey there! I'm currently working on an Ajax jQuery function that displays table data, like in the image provided. I would like to add an option for users to edit and delete the table data, with the changes reflecting in the database. It's worth n ...

The typescript MenuProvider for react-native-popup-menu offers a range of IntrinsicAttributes

Looking to implement drop-down options within a Flatlist component, I've utilized the React Native Popup Menu and declared MenuProvider as the entry point in App.tsx. Encountering the following error: Error: Type '{ children: Element[]; }' ...

Organize the array by property name and include a tally for each group

My current data structure looks like this: var data = [ { MainHeader: Header1, SubHeader: 'one'}, { MainHeader: Header1, SubHeader: 'two'}, { MainHeader: Header2, SubHeader: 'three'}, { MainHeader: Header2, SubHea ...

Is there a way to adjust the image opacity of a background using Material UI?

Is there a way to adjust the opacity of a background image using Material UI? I attempted to achieve this by utilizing the makeStyles hook in Material UI. Here is an example of my code: import React from 'react'; import {Box,Typography } from &ap ...

Show a pop-up notification when the quantity in one set of cells matches the quantity in a different set of cells

Does anyone have a script that can show a popup message when the count of yellow cells matches the count of red cells? Here is a visual representation of what I'm looking for. Any assistance would be greatly appreciated. https://i.sstatic.net/2bJsx.p ...

Discover a revolutionary Android app that provides detailed indoor maps and step-by-step walking directions

I am looking to enhance a custom Google map by adding sidewalks for walking, while keeping all of its original features intact. Additionally, I want to create a detailed interior map of a building on a college campus, complete with classroom locations on ...

"Encountering errors during npm installation due to a failed preinstall

Having identified security vulnerabilities for knexnest > knex > minimist, I encountered an issue where the minimist version did not update using npm audit fix or a simple npm update. Following the steps outlined in this informative article resolved ...

Show a modal when the axios request is finished

EDIT: After some exploration, I've shared the solution I found in case it helps others facing a similar issue. I'm currently working on building a reusable Bootstrap 5 modal child component within Vue3. The goal is to pass an ID as a prop from t ...

Step-by-step guide for dynamically including dropdown options

Is there a way to dynamically add a dropdown using JavaScript? I currently have a dropdown with numbers that creates another dropdown when selected. However, I want to add the dynamic dropdown through JavaScript. How can I achieve this? Below is the PHP ...

Leveraging the power of mapState and mapMutations within a namespaced module

I'm having trouble accessing mutations and states after dividing my Vuex store into three modules. I've attempted various syntaxes, but none seem to be working for me. MapStates: This is how I have set up the mapStates, with 'vendor' a ...

DNN Unveils New "Exit Confirmation" Pop-up Feature When Clicking External Links

Greetings fellow beginners! I've been struggling to make some changes on our DNN site (Evoq 8.5) with no success so far. The issue at hand is that we have links throughout our entire website that follow this format: <a href="www.site.com" class="e ...