Leaflet.js and PostGIS – Transferring Point Information to a Function

leafletpostgis

I'm trying to extract some information from a L.geojson feature of the map, containing points, through a newly created button inside a BindPopup feature, pointing to a function. Such function then writes the information to the cookies, and calls a PHP file through Ajax to write a new point in a Postgis database, with hopefully some informations attached.

The informations that I'm interested in are :

  • lat and lng of the point
  • the value that has been created or
    modified in "default_cat"
  • the name as in feature.properties.name

All this would allow me to create points in a Postgis database.

This is the PHP called by ajax. It has been working with simple markers created out of nothing and including a "notes" value. (The bindValue name line has just been added, though). It is from Leaflet CRUD (link) and modified

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once dirname(__FILE__) . '/./dbconfig.php';
header("Access-Control-Allow-Origin: *");


$dbcon = new PDO("pgsql:host=".$dbconfig['_pgsql_db_host_'].";port=".$dbconfig['_pgsql_db_port_'].";dbname=mfy_".$_COOKIE['user_id'].";user=".$dbconfig['_pgsql_db_user_'].";password=".$dbconfig['_pgsql_db_pass_']."");
$dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbcon->prepare("INSERT INTO data_bookmarks (notes,name,geom) VALUES(LOWER(:notes),LOWER(:name),ST_SetSRID(ST_MakePoint(".$_COOKIE['tmplng'].",".$_COOKIE['tmplat']."),4326));");
$stmt->bindValue(":notes", $_COOKIE['tmpcat'], PDO::PARAM_STR);
$stmt->bindValue(":name", $_COOKIE['tmpname'], PDO::PARAM_STR);
$stmt->execute()
?>

I'm first creating the temporary layer holding the bookmarks, creating the function. Xhrfields, in Ajax, allows to pass the cookies.

let tmpbookmarks = L.layerGroup().addTo(map);


function bookmarkpoi() {
    L.marker(e.latlng).addTo(tmpbookmarks);

    document.cookie = 'tmpname='+feature.properties.name+'; expires=Wed, 1 Jan 2070 13:47:11 UTC; path=/';
    document.cookie = 'tmpcat='+default_cat+'; expires=Wed, 1 Jan 2070 13:47:11 UTC; path=/';
    document.cookie = 'tmplat='+e.latlng.lat+'; expires=Wed, 1 Jan 2070 13:47:11 UTC; path=/';
    document.cookie = 'tmplng='+e.latlng.lng+'; expires=Wed, 1 Jan 2070 13:47:11 UTC; path=/';
                  
               $.ajax({
                   url: "../crud/dataservice/create_bookmark.php",
                   method: "GET",
                     xhrFields: {
         withCredentials: true
      }
   });      
};

And this are the points, bind together in Leaflet Markerclusters, called by Leaflet Wfs and exported to Geojson. A bindpopup holds a button to the function, but it won't allow me to pass the latitude, longitude, name and default category to the function…

var mc_barrest = new L.MarkerClusterGroup({
    // maxClusterRadius: 250,
    // minClusterRadius: 7,
       // spiderfyDistanceMultiplier: 1.2,
        zoomToBoundsOnClick: false,
        disableClusteringAtZoom: 17,
        spiderfyOnEveryZoom: true,
        spiderLegPolylineOptions: {
            weight: 0,
            opacity: 0,
          },
       // spiderfyOnMaxZoom: true,
       iconCreateFunction:  createClusterCustomIcon
    });
    
    var startatzoom_barrest = 9;
var featureLayer_barrest = new L.GeoJSON(
    null, {
        //  style: styled(color= 'Peru', fillColor = 'Peru'),
        pointToLayer: function(feature, latlng) {
            switch (feature.properties.amenity) {
                case 'cafe':
                    return L.marker(latlng, {
                        icon: L.ExtraMarkers.icon({
                            icon: 'fa-coffee',
                            markerColor: 'orange',
                            shape: 'circle',
                            prefix: 'fa'
                        })
                    });
                case 'ice_cream':
                    return L.marker(latlng, {
                        icon: L.ExtraMarkers.icon({
                            icon: 'fa-ice-cream',
                            markerColor: 'orange',
                            shape: 'circle',
                            prefix: 'fa'
                        })
                    });
                    
             }
        },
        
        
      onEachFeature: function popUpsome(feature, layer) {

            let default_cat = "";
            if (feature.properties.amenity) {
                default_cat = feature.properties.amenity + '. ';
            };

            if (feature.properties.amenity_1) {
                default_cat = default_cat + ' ' + feature.properties.amenity_1 + '. ';
            };


            let reply_description = "";
            if (feature.properties.description) {
                reply_description = "<br>" + feature.properties.description;
            };
            
            
            
                 if (feature.properties.name) {
                reply_name = feature.properties.name;
            } else {
                reply_name = default_cat;
                default_cat = "";

            };

            if (feature.properties) {
                layer.bindPopup('<button onclick="bookmarkpoi(feature.properties.lat, feature.properties.lng, feature.properties.name)">📍Bookmark me</button><p class="tooltip-title" style="font-size: 16px;">' + reply_name + '</p><p class="bind-text"><b>' + default_cat + '<br><p>' + reply_description + '</p>', {
                    maxWidth: 200,
                    maxHeight: 200,
                    autoClose: false,
                    closeOnClick: null
                });

                layer.bindTooltip(reply_name,                       
                    {permanent: true,
                      autoClose: false,
                    closeOnClick: null,
                    opacity: 0.7});
                    
                    setTimeout(closeInfotool, 10000);            }
        }

    });

    function loadGeoJson_barrest(data) {
        red = 255;
        green = 140;
        blue = 0; 
        featureLayer_barrest.clearLayers();
        mc_barrest.clearLayers();
        featureLayer_barrest.addData(data);
        mc_barrest.addLayer(featureLayer_barrest);
        map.addLayer(mc_barrest);
    };
    
function load_wfs_barrest() {
    if (map.getZoom() > startatzoom_barrest) {
        var geoJsonUrl = 'https://website.com/geoserver/wfs?';
        var defaultParameters = {
            service: 'WFS',
            version: '1.0.0',
            request: 'getFeature',
            typeName: wfs_barrest,
            maxFeatures: 250,
            outputFormat: 'text/javascript',
            format_options: 'callback: getJson_barrest',
            srsName: 'EPSG:4326'
        };

        var customParams = {
            bbox: map.getBounds().toBBoxString()
        };

        var parameters = L.Util.extend(defaultParameters, customParams);
        //       console.log(geoJsonUrl + L.Util.getParamString(parameters));

        $.ajax({
            jsonp: false,
            url: geoJsonUrl + L.Util.getParamString(parameters),
            dataType: 'jsonp',
            jsonpCallback: 'getJson_barrest',
            success: loadGeoJson_barrest
        });
    } else {
        featureLayer_barrest.clearLayers();
        mc_barrest.clearLayers();
    }
};

enter image description here

Best Answer

I was able to fix it adding a class: on("popupopen", after bindPopup

var featureLayer_hebergement = new L.GeoJSON(
    null, {
        //  style: styled(color= 'Peru', fillColor = 'Peru'),
        pointToLayer: function(feature, latlng) {
            switch (feature.properties.tourism) {
                case 'camp_site':
      
....

  onEachFeature: function popUpsome(feature, layer) {

           ....

   if (feature.properties) {
                layer.bindPopup('<button class="bookm">📍Bookmark me</button><p class="tooltip-title" style="font-size: 16px;">' + reply_name + '</p><p class="bind-text"><b>' + default_cat + '</b>' + reply_stars + reply_description + '<i>' + reply_opening_hours + '</i><small><br>' + reply_internet_access + reply_swimming_pool + reply_dog + '</small>' + reply_phone + reply_email + reply_website + '</p>', {
                    maxWidth: 200,
                    maxHeight: 200,
                    autoClose: false,
                    closeOnClick: null
                }).on("popupopen", () => {
                    $(".bookm").on("click", e => {
                      e.preventDefault();
   // var latlng = map.mouseEventToLatLng(e.originalEvent);
   var objlat =  feature.geometry.coordinates[1];
   var objlng =  feature.geometry.coordinates[0];
                      document.cookie = 'tmpname='+feature.properties.name+'; expires=Wed, 1 Jan 2070 13:47:11 UTC; path=/';
                      document.cookie = 'tmpcat='+default_cat+'; expires=Wed, 1 Jan 2070 13:47:11 UTC; path=/';
                      document.cookie = 'tmplat='+objlat+'; expires=Wed, 1 Jan 2070 13:47:11 UTC; path=/';
                      document.cookie = 'tmplng='+objlng+'; expires=Wed, 1 Jan 2070 13:47:11 UTC; path=/';
                                                                   $.ajax({
                                     url: "../crud/dataservice/create_bookmark.php",
                                     method: "GET",
                                       xhrFields: {
                           withCredentials: true
                        }
                     }); 

                    });
                  });