Error: Unable to load L.GeometryField constructor in django-leaflet library

I'm having trouble saving a geolocation to a Postgres database using Django-leaflet. I keep getting an error message that says

Uncaught TypeError: L.GeometryField is not a constructor
. My code involves AJAX calls.

    <script>
      var csrftoken = "{{ csrf_token }}";

      function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
      }

      $.ajaxSetup({
        beforeSend: function(xhr, settings) {
          if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
          }
        }
      });

       
  </script>
{% endblock %}
<strong>Location Input:</strong>

<p id="demo" onload="getLocation()"></p>


<form method="post" >
  {% csrf_token %}
  {{ form.as_p }}
</form>
<script type="text/javascript">

      var x=document.getElementById("demo").addEventListener("change",save_data);       

       function getLocation()
         {
        if (navigator.geolocation)
        {
        navigator.geolocation.getCurrentPosition(showPosition);
        }
        else{x.innerHTML="Geolocation is not supported by this browser.";}
        }
        function showPosition(position)
        {
        x.innerHTML="Latitude: " + position.coords.latitude + 
        "<br>Longitude: " + position.coords.longitude;

        }
        function save_data(){
          var token=$("{{ csrf_token }}");
          var pos =$("#demo").val();
          console.log("THIS IS:",x);
          $.ajax({
            type:"POST",
            headers:{"X-CSRFToken":token},
            url: "{% url 'shop:user-create' %}",
            data:{pos:pos},

          });
        } 
      
</script>

Error:

<script type="text/javascript">
    var geodjango_id_user_loc = {};
    geodjango_id_user_loc.fieldid = 'id_user_loc';
    geodjango_id_user_loc.modifiable = true;
    geodjango_id_user_loc.geom_type = 'Point';
    geodjango_id_user_loc.srid = 4326;
    

    function id_user_loc_map_callback(map, options) {
        geodjango_id_user_loc.store_class = L.FieldStore;
        (new L.GeometryField(geodjango_id_user_loc)).addTo(map);
        
    };

    
</script>

Answer №1

Dealing with the same problem, I found a solution that involved including plugins="forms" in both {% leaflet_js %} and {% leaflet_css %}

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

The custom filter in AngularJS fails to activate

Currently, I have a filter function that looks like this: 'use strict'; angular.module('app') .filter('fromNow', function() { return function(date) { return moment(date).fromNow(); } }); ...

VueJS error: Trying to access properties of undefined object ('$refs') is unsuccessful

Parent Component: ... <v-stepper-step :rules="[()=>isValid(1)]" > MyStep </v-stepper-step> <v-stepper-content> <Mytag ref="MyReference" /> </v-stepper-content> ... methods: { isValid(number){ ...

An easy way to activate a toggle function when the page loads in React

I want to create a nice slide-in effect for my sidebar when the user loads the page. My goal is to toggle the state of the Sidebar component from open: false to open: true on load in order to achieve this effect. Unfortunately, it seems that the way I&apo ...

What is the best way to prevent two paths within an SVG from intersecting with each other?

Currently, I am developing a program that allows the user to draw lines. Once the user completes drawing a line, I receive an array of points in this format: [[x, y], [x, y], ...]. I then convert these points into a path string using the following functio ...

Is there a way for me to gain access to the ng-repeat scope?

I have a scenario where my ng-repeat generates different elements and I need to perform certain operations, such as creating variables, within the scope of the ng-repeat. Is there a way to access the specific ng-repeat scope? How can I achieve something ...

Exploring the power of Javascript for number lookup

I am currently working on a coding project using TypeScript and JavaScript to locate a specific number provided by the user within a list. The goal is to display whether or not the number is present in the list when the 'search' button is pressed ...

Token mismatch detected despite the presence of a valid CSRF token

I am making an AJAX call for a method using AJAX and Laravel. I have placed the token on the head of my blade file and sent it with the form, but I am encountering an error 219 'csrf token mismatch'. I can't seem to figure out why I am getti ...

Notifying with Socket.IO in Node.js

Hey there, I'm currently working on implementing a notification system but have hit a roadblock. I've sent an invitation to a user to join the club. socket.on("notify", async (message) => { // invite the user John Doe io.to('socke ...

Access an HTML element and using JavaScript to make changes to it

As a new web developer, I am eager to create a grid of file upload zones on my site. I have decided to use DropZone.js for this project. I have customized DropZone and added multiple drop zones in the HTML. The grid layout consists of four rows with four ...

The hide-columns feature in Ng-table does not allow for manual column hiding from the controller

I've configured ng-table with checkboxes to toggle column visibility, and it's functioning smoothly. Here's the HTML: // Switchers to show/hide columns <div style="margin-bottom: 20px"> <label class="checkbox-inline" ng-repeat= ...

What causes the disparity between Chrome's print preview and printed output? [HTML - CSS]

In my Angular demo project, I have included basic text and a table. There is a print button that calls window.print() to print the page with applied styling. printPage() { window.print(); } CSS: @media print { @page { size: landscap ...

The JQuery onchange event functions as expected multiple times within JSFiddle, but seems to only fire once in the

A jQuery (1.11.1) script has been implemented on a business catalyst site cart page to show or hide a message based on the dropdown option selected by the user. The script functions correctly multiple times in jsfiddle at http://jsfiddle.net/NathanHill/462 ...

Issues with AngularJS checkbox input failing to register properly on mobile devices?

Inside the ng-repeat, there is an input checkbox structured like this: <div class="provisions"> <label ng-repeat="(key, value) in data"> <div class="innerProvision"> <input class="provisionCheck" type="checkbox ...

Increase the Value of a Model Using the Power of Ajax and Razor

While iterating through a collection in my model using Razor to render it, one scenario could be: @foreach(var item in myCollection) { <span id='<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b425f4e46066b425f4e46 ...

The navigation icon on my website refuses to close

Hey there, I'm having some trouble creating a side navigation menu. The issue I am facing is that the menu opens without any problem, but then I can't seem to figure out how to close it using a second "onclick()" function. If you could take a lo ...

What is the best way to display the original array when the search input for the title is left blank?

When I enter a todo item title in the search input field and then clear the search input, I expect the initial array of todos to be rendered again. I attempted to accomplish this using an if statement but it did not work - only the previously searched todo ...

Initiate the 'Prolonged Wait' Script upon Page Launch, Utilizing AJAX to Verify Completion

I am currently facing a challenge with my webpage where I need to embed a script that could potentially take up to 10 minutes to run on the backend. After trying various versions of an ajax script loader with a timer, I have not been successful in achievi ...

What is the most efficient method for locating the smallest and largest values in a list of elements?

One array contains numbers and the other contains names. Here's an example: A: 4, B: 3, C: 2, A: 5, C: 3, My goal is to identify the elements with the smallest and largest values. I am aware that I could create an array of objects and sort it using m ...

Provide a TypeScript interface that dynamically adjusts according to the inputs of the function

Here is a TypeScript interface that I am working with: interface MyInterface { property1?: string; property2?: string; }; type InterfaceKey = keyof MyInterface; The following code snippet demonstrates how an object is created based on the MyInter ...

Is it possible for the await block to be located outside of the async function that contains it?

setInterval(() => { // perform certain actions }, 1000) const bar = async () => { const response = await api_request(); do_actions(); } await bar(); When the foo function is set to run, will it interfere with the execution of the setInterval ...